Skip to main content
 首页 » 编程设计

python之MysqlDB调用TypeError : 'int' object is not iterable python

2024年08月21日21think

我正在运行如下查询:

SELECT post_title, post_name FROM wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3 

输出如下信息:

ID   post_title       post_name 
1    a title here     a-title-here 
2    a title here2     a-title-here2 
3    a title here3     a-title-here3 

并尝试在 app.py 中为 flask 调用它:

@app.route('/', methods=('GET', 'POST')) 
def email(): 
        blogposts = c.execute("SELECT post_title, post_name FROM wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3") 
 
        return render_template('index.html', form=form, blogposts=blogposts) 

在我的模板中,我将 blogposts 称为:

    {% for blogpost in blogposts %} 
    <li><a href="{{blogpost[1]}}">{{blogpost[0]}}</a></li> 
    {% else %} 
    <li>no content...</li> 
    {% endfor %} 

但是我得到一个错误:

    {% for blogpost in blogposts %} 
TypeError: 'int' object is not iterable 

我做错了什么?

请您参考如下方法:

Python MySQL(和其他数据库)连接器中的 .execute 调用不直接返回数据库结果。 (在这种情况下,它返回匹配记录的数量)。

您必须进一步调用数据库驱动程序以检索实际的select 结果。更简单的方法是 .fetchall() 方法,它将以列表的形式返回所有选定的结果。

简而言之,将对这两行的调用更改为 execute:

... 
c.execute("SELECT post_title, post_name FROM wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3") 
blogposts = c.fetchall()