python - 如何使用 Python 和 MySQL 连接器检索数据

标签 python mysql mysql-connector

我有一个 MySQL 数据库,其中包含一个包含服务(google、reddit 等)和密码的表。我想查询 db (SELECT * FROM pwds) 并将它们添加到 Python dict 中,以便 dict 的键是服务,值是密码。例如,Passwords['google']='G4sR0*KMVC'。这是我到目前为止所拥有的:

Passwords = {} #Dictionary to store service and password
cnx = mysql.connector.connect(user='Bob', password='foobar', host='127.0.0.1', database='passwords')
query = ("SELECT * FROM pwds")
cursor = cnx.cursor(dictionary=True)
cursor.execute(query)

当我在 iPython 中运行它时,在最后一步之后,我可以看到光标中的内容 enter image description here

如何获取字典中光标处的内容?我一直在尝试不成功,我想不通。

最佳答案

应该这样做:

passwords = dict([(row["service"], row["password"]) for row in cursor])

或者使用字典理解(在 Python 2.7+ 中可用):

passwords = {row["service"]: row["password"] for row in cursor}

关于python - 如何使用 Python 和 MySQL 连接器检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34773514/

相关文章:

python - 从 CSV 文件中提取最后一行并将其放入另一个文件中,并使用 Python 中的文件名

java - 如何在 python/jython 中执行此操作(用 java 编码)?

python - Django NoReverseMatch 命名空间错误

php - 使用 95% 标签的图像无法正常工作

mysql - 无法从mysql中的记录中打印出最大值

php - "Registration-form"创建多个用户

c# - 如何更改与 MySQLConnector/Net 中的连接关联的时区?

python - SQLite3 Python : How to do an efficient bulk update?

c# - Nant 在 GAC 中找不到程序集

python - 如何通过 MySQLdb Python 将值插入表中