【问题标题】:MySQL-python: SELECT returns 'long' instead of the queryMySQL-python:SELECT 返回“long”而不是查询
【发布时间】:2013-08-21 23:53:31
【问题描述】:

我在使用mysql-python 在已建立的数据库上运行选择查询时遇到问题。问题是返回一个数字,Python 称为 long,而不是查询的数据 - 应该注意,这个数字对应于应该返回的记录数(我登录到数据库并从MySQL 运行查询以确保)。

代码如下:

db = MySQLdb.connect(db = 'testdb', user='testuser', passwd='test', host='localhost', charset='utf8', use_unicode=True)
dbc = db.cursor()
result = dbc.execute("""SELECT %s FROM example_movie""", ('title',))
urls = [row[0] for row in result]

最后一段代码urls = [row[0] for row in result] 是将所有内容放入一个列表中。

错误如下所示:

 TypeError: 'long' object is not iterable

当我有 python print result 它返回:

('RESULT:', 52L)

当我将resultstr(result) 括起来时,它只返回数字52(不是long

非常感谢任何帮助和建议!

【问题讨论】:

    标签: mysql select mysql-python


    【解决方案1】:

    dbc.execute的返回值不是select的结果;我相信这是结果中的行数。为了获得实际结果,您需要调用fetch 方法之一。请参阅文档here

    您应该将代码更新为:

    db = MySQLdb.connect(db = 'testdb', user='testuser', passwd='test', host='localhost', charset='utf8', use_unicode=True)
    dbc = db.cursor()
    row_count = dbc.execute("""SELECT title FROM example_movie""")
    results = dbc.fetchall()
    urls = [row[0] for row in result]
    

    【讨论】:

    • 您好,感谢您抽出宝贵时间回复!当我执行此操作时,它只打印一个[u'title,...., u'title] 的大列表。有没有办法真正获得这些电影的片名?
    • 其实!如果我只是做dbc.execute("""SELECT title FROM example_movie"""),那就可以了! (与我使用的方法相反)。我会将您的答案标记为接受!随意添加这一点。
    • @FortyLashes,不能参数化列名,参数变成字符串文字,你在输出中看到它们。
    猜你喜欢
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 2020-08-31
    相关资源
    最近更新 更多