【问题标题】:Fetchall returning only one column in Python?Fetchall 在 Python 中只返回一列?
【发布时间】:2012-12-21 02:59:10
【问题描述】:

我有一个这样的代码:

db = MySQLdb.connect(user='root', db='galaxy', passwd='devil', host='localhost')
cursor = db.cursor()
cursor.execute('SELECT username, password FROM galaxy_user')
names = [row[0] for row in cursor.fetchall()]
passw = [password[1] for password in cursor.fetchall()]
db.close()

问题是我只能从以下代码访问名称或密码。有了这个我只能得到用户名。我得到了密码的空列表。现在,如果我像这样切换:

passw = [row[1] for row in cursor.fetchall()]
names = [password[1] for password in cursor.fetchall()

我得到了 passw 的值,但名称是空列表。发生了什么?

【问题讨论】:

    标签: python mysql-python


    【解决方案1】:

    在每个cursor.execute 之后,您只能使用一次cursor.fetchall。它“耗尽”游标,获取所有数据,然后无法再次“读取”。

    使用以下代码,您可以同时读取所有数据:

    db = MySQLdb.connect(user='root', db='galaxy', passwd='devil', host='localhost')
    cursor = db.cursor()
    cursor.execute('SELECT username, password FROM galaxy_user')
    names, passw = zip(*cursor.fetchall())
    db.close()
    

    另一种可能性是将所有数据存储在一个列表中,然后像游标一样读取它:

    records = cursor.fetchall()
    names = [record[0] for record in records]
    passw = [record[1] for record in records]
    

    或者字典(名称 -> 密码)怎么样?

    user_pass = dict(cursor.fetchall())
    

    或者简单地说(正如@JonClemens 建议的那样):

    user_pass = dict(cursor)
    

    【讨论】:

    • 我认为这里的关键是 .fetchall() 似乎有点多余,因为光标应该是可迭代的......要么,list(cursor) 要么我喜欢你的 dict(cursor) 想法 :)
    • @eumiro,我刚刚使用 Python cx_Oracle 进行了测试:records = cursor.fetchall() names = [record[0] for record in records] passw = [record[1] for record in records] 和名称为无。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多