dictonary

Gerhard Häring gh_pythonlist at gmx.de
Wed Mar 13 05:49:21 EST 2002


Le 13/03/02 à 11:20, Daniel Nygård écrivit:
> How do I insert a dictionary into a database (_mysql)?

Don't use _mysql. Use MySQLdb instead.

> db = _mysql.connect()
> string = {
> 	hello:'wow', 
> 	something:'nothing',
> 	nothing : 'something',
> 	number : 5,
> 	name : 'daniel'}
> 
> then I have a database with the same attributes as the keys in the dict.
> above.
> How do I insert the whole dict into the database.
 
This is one way to do it, I bet there's a better one:

dict = {'name': 'Andy', 'age': 39}

columns = ",".join(dict.keys())
# I hope using only %s works for MySQLdb. It does work like this for pyPgSQL.
placeholders = ",".join(['%(' + k + ')s' for k in dict.keys()])
sql = "insert into table(" + columns + ") values (" + placeholders + ")"

# This should do the proper parameter quoting:
cursor.execute(sql, dict)

The author of MySQLdb has a module called SQLDict on his homepage (just
google for it). Maybe you'll find it useful.

Cheers,

Gerhard
-- 
This sig powered by Python!
Außentemperatur in München: 16.0 °C      Wind: 1.7 m/s




More information about the Python-list mailing list