Use a python dictionary to insert into mysql

我们两清 提交于 2019-12-21 05:52:22

问题


I am trying to take the data from a dictionary (the example is simplified for readability) and insert it into a mysql database. I have the following piece of code.

import pymysql 
conn = pymysql.connect(server, user , password, "db")
    cur = conn.cursor()
    ORFs={'E7': '562', 'E6': '83', 'E1': '865', 'E2': '2756 '}
    table="genome"
    cols = ORFs.keys()
    vals = ORFs.values()
    sql = "INSERT INTO %s (%s) VALUES(%s)" % (
    table, ",".join(cols), ",".join(vals))

    print sql
    print ORFs.values()
    cur.execute(sql, ORFs.values())


    cur.close()
    conn.close()

the print sql statement returns
INSERT INTO genome (E7,E6,E1,E2) VALUES(562,83,865,2756 )
when I type this directly into the mysql command line, the mysql command works. But when I run the python script I get an error:

<type 'exceptions.TypeError'>: not all arguments converted during string formatting
      args = ('not all arguments converted during string formatting',)
      message = 'not all arguments converted during string formatting' 

As always, any suggestions would be highly appreciated.


回答1:


sql = "INSERT INTO %s (%s) VALUES(%s)" % (
    table, ",".join(cols), ",".join(vals))

This SQL includes values and cur.execute(sql, ORFs.values()) has values, too.

So, it should be cur.execute(sql).




回答2:


The previous answer doesn't work for non string dictionary value. This one is a revised version.

    format_string = ','.join(['%s'] * len(dict))
    self.db.set("""INSERT IGNORE INTO listings ({0}) VALUES ({1})""".format(", ".join(dict.keys()),format_string), 
                         (dict.values()))



回答3:


In my case, I will skip null columns.

data = {'k': 'v'}
fs = ','.join(list(map(lambda x: '`' + x + '`', [*data.keys()])))
vs = ','.join(list(map(lambda x: '%(' + x + ')s', [*data.keys()])))
sql = "INSERT INTO `%s` (%s) VALUES (%s)" % (table, fs, vs)
count = cursor.execute(sql, data)


来源:https://stackoverflow.com/questions/33336963/use-a-python-dictionary-to-insert-into-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!