【发布时间】:2012-11-04 20:20:16
【问题描述】:
我正在尝试使用 mysql-flask python 扩展执行一些 sql。由于某种原因,下面的代码总是返回一个 long。
stringify = lambda x : '"' + x + '"'
if request.method == 'POST':
sql = "select * from users where username = " + stringify(request.form['username'])
user = g.db.cursor().execute(sql).fetchall()
错误:
user = g.db.cursor().execute(sql).fetchall()
AttributeError: 'long' object has no attribute 'fetchall'
为什么不返回结果集?
另外,我可以很好地执行插入语句。
修复(答案):
def get_data(g, sql):
cursor = g.db.cursor()
cursor.execute(sql)
data = [dict((cursor.description[idx][0], value) for idx, value in enumerate(row)) for row in cursor.fetchall()]
return data
【问题讨论】:
-
您可能还想研究字符串格式,尤其是使用 execute 函数。你可以写
sql = 'select * FROM users where username="%s"',然后写cursor.execute(sql, (request.form.username,))(见这里的例子mysql-python.sourceforge.net/MySQLdb.html#cursor-objects)