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

标签 python mysql-python

我有一个这样的代码:

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/

相关文章:

python - Django migrate error _mysql_exceptions.ProgrammingError : (1064, "你的SQL语法有错误

python - django 中的复合数据库

python - 每个连接有多个事务的 MySQLdb

python - 如何使用 mysql 验证 flask/python 中的凭据?

python - 如何通过对列进行分区来高效地生成这个字典?

Python 字符串段操作

python - 使用 python 在 Linux 中合并文件时文件大小大大减少

python - 我可以以及如何将参数传递给聚合中使用的多个函数?

python - Pipeline.py 显示异常

Python MySQLdb编程错误: 1064 when inserting data