gpt4 book ai didi

python - Fetchall 在 Python 中只返回一列?

转载 作者:太空狗 更新时间:2023-10-30 00:30:14 34 4
gpt4 key购买 nike

我有一个这样的代码:

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 的空列表。现在,如果我这样切换:

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

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

最佳答案

在每次 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)

关于python - Fetchall 在 Python 中只返回一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14194969/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com