我有一个 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 中运行它时,在最后一步之后,我可以看到光标中的内容
如何获取字典中光标处的内容?我一直在尝试不成功,我想不通。
最佳答案
应该这样做:
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/