简体   繁体   中英

MySQLdb inserting a dict into a table

I have a row of data in dict format. Is there an easy way to insert it into a mysql table. I know that I can write a custom function to convert dict into a custom sql query, but I am looking for a more direct alternative.

Well... According to the documentation for paramstyle :

Set to 'format' = ANSI C printf format codes, eg '...WHERE name=%s'. If a mapping object is used for conn.execute(), then the interface actually uses 'pyformat' = Python extended format codes, eg '...WHERE name=%(name)s'. However, the API does not presently allow the specification of more than one style in paramstyle

So, it should be just a matter of:

curs.execute("INSERT INTO foo (col1, col2, ...) VALUES (%(key1)s, %(key2)s, ...)", dictionary)

where key1 , key2 , etc. would be keys from the dictionary.

Disclaimer: I haven't tried this myself :)

Edit: yeah, tried it. It works.

MySQLDB does not come with anything which allows a direct operation like that. This is a common problem with a variety of answers, including a custom function for this purpose.

In my experience, it is best to buckle down and just write the paramaterized SQL most of the time. If you have the same thing going on a lot, then I would consider factoring it into a utility function.

HOWEVER, if you are hand-writing static SQL using parameters, then most of the security and bug related issues are taken care of. When you start basing your SQL on a dictionary of data that came from where (?), you need to be much more careful.

In summary, your code will likely be more readable and maintainable and secure if you simply write the queries, use parameters, and document well.

(Note: some proponents of ORM, etc... may disagree... this is an opinion based on a lot of experience on what was simple, reliable, and worked for our team)

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