简体   繁体   English

使用python字典插入mysql

[英]Use a python dictionary to insert into mysql

I am trying to take the data from a dictionary (the example is simplified for readability) and insert it into a mysql database. 我正在尝试从字典中获取数据(为便于阅读,示例被简化了)并将其插入到mysql数据库中。 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 print sql语句返回
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. 当我直接在mysql命令行中键入此命令时,mysql命令有效。 But when I run the python script I get an error: 但是当我运行python脚本时出现错误:

<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. 与往常一样,任何建议将不胜感激。

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()))
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. 此SQL包含值,并且cur.execute(sql, ORFs.values())也具有值。

So, it should be cur.execute(sql) . 因此,应该为cur.execute(sql)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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