简体   繁体   中英

How to retrieve data using Python and MySQL connector

I have a MySQL database with a table holding a service (google, reddit, etc) and a password. I want to query the db (SELECT * FROM pwds) and add them to a Python dict, so that the key of the dict is the service, and the value the password. Passwords['google']='G4sR0*KMVC', for example. Here's what I have so far:

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)

When I run this in iPython, after the last step, I can see what's in the cursor 在此处输入图片说明

How can I get what's in the cursor in my dictionary? I've been trying unsuccessfully, and I can't figure it out.

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)

for row in cursor:
    Passwords[row['service']] = row['password']

This might be what you're looking for.
Since the rows are actually returned as dict from the mysql library, you'll access the individual row "columns" as any other dict.

In short, since a dictionary works by assigning key to value like so:

myDict = {key : val, key : val}

With each key being unique, you'll access them with whatever is in the key.

myDict = {'name' : 'Torxed', 'type' : 'Funny guy'}
myDict['name']

The only difference between mysql and the dictionary above is that mysql returns a dictionary for each row, but it will be accessed the same way for each individual row.

mysqlRows = [ {'name' : 'Torxed', 'type' : 'Funny guy'}, {'name' : 'Amanda', 'type' : 'Has a panda?'} ]
for row in mysqlRows:
    print['name']

And what you want, is to take the values from your mysql results and store them in your own key-slot in your own dictionary :

Passwords[key] = val

Which translates to:

Passwords[ row['service'] ] = row['password']

This should do it:

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

Or using a dictionary comprehension (available in Python 2.7+):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM