【问题标题】:AttributeError: 'long' object has no attribute 'fetchall'AttributeError: 'long' 对象没有属性 'fetchall'
【发布时间】: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

【问题讨论】:

标签: python mysql flask


【解决方案1】:

您正在尝试对Cursor.execute 的结果调用一个方法,DB-API specification 表示该方法未定义(您使用的实现似乎返回一个整数)。相反,您想在光标对象上调用fetchall。比如:

cursor = g.db.cursor()
cursor.execute(sql)
user = cursor.fetchall()

【讨论】:

  • 知道如何把它变成字典吗?看起来返回的对象非常原始。如果没有关于返回哪些列的更多信息,不确定我们如何设置键,即调用 dict() 是不够的。
  • 您可以使用光标上的description 属性来确定列是什么。也就是说,如果您询问您所追求的数据而不是询问所有列,您的代码将更加健壮(这样您应该事先知道每个元组项是什么)。如果您需要更高级别的接口,或许可以考虑使用像 Storm、SQLAlchemy 或 Django 的 ORM 这样的 ORM。
  • 我肯定会使用 SqlAlchemy,但这个项目的要求不允许使用 ORM
  • 知道了: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()] 返回数据
猜你喜欢
  • 2021-05-12
  • 1970-01-01
  • 2017-12-08
  • 2012-12-01
  • 2021-04-19
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2018-08-28
相关资源
最近更新 更多