使用python字典插入到mysql中 [英] Use a python dictionary to insert into mysql

查看:498
本文介绍了使用python字典插入到mysql中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字典中获取数据(该示例简化为可读性),并将其插入到mysql数据库中。
我有以下代码。

  import pymysql 
conn = pymysql.connect(server,用户密码db)
cur = conn.cursor()
ORFs = {'E7':'562','E6':'83','E1':'865' 'E2':'2756'}
table =基因组
cols = ORFs.keys()
vals = ORFs.values()
sql =INSERT INTO%s (%s)VALUES(%s)%(
table,,。join(cols),,。join(vals))

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


cur.close()
conn.close()

print sql 语句返回

INSERT INTO基因组(E7,E6,E1,E2)值(562,83,865,2756)

当我直接输入到mysql命令行,mysql命令工作。但是当我运行python脚本时,我会收到一个错误:

 < type'exceptions.TypeError'> ;:不是所有的参数在字符串格式化期间转换
args =('并非所有参数在字符串格式化过程中转换')
message ='不是所有参数在字符串格式化过程中转换'
pre>

与往常一样,任何建议将非常感激。

解决方案

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

此SQL包含值和 cur.execute(sql,ORFs



所以,应该是 cur.execute(sql) / code>。


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.

解决方案

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).

这篇关于使用python字典插入到mysql中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆