python 字典 插入mysql,使用python字典插入到mysql中

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:

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python如何使用字典将数据存入MySQL数据库? 首先,你需要安装MySQL驱动程序,可以使用`pip`命令来安装`mysql-connector-python`库。 ``` pip install mysql-connector-python ``` 接下来,你需要引入该库并创建一个MySQL连接。你需要提供数据库的主机名、用户名、密码和数据库名称。 ```python import mysql.connector # 建立与MySQL数据库的连接 cnx = mysql.connector.connect( host="localhost", user="your_username", password="your_password", database="your_database" ) ``` 创建连接后,你可以创建一个游标对象,并使用它执行SQL查询和操作。 ```python # 创建游标对象 cursor = cnx.cursor() # 创建一个表格(如果不存在) create_table_query = """ CREATE TABLE IF NOT EXISTS my_table ( id INT PRIMARY KEY, name VARCHAR(255), age INT ) """ cursor.execute(create_table_query) ``` 接下来,你可以使用字典将数据插入到表格。 ```python # 要插入的数据 data = { 'id': 1, 'name': 'John', 'age': 25 } # 插入数据 insert_query = """ INSERT INTO my_table (id, name, age) VALUES (%(id)s, %(name)s, %(age)s) """ cursor.execute(insert_query, data) # 提交更改并关闭连接 cnx.commit() cursor.close() cnx.close() ``` 以上代码将在名为`my_table`的表插入一条记录。你可以根据自己的需求修改表的结构和插入的数据。 注意:在实际开发,你可能需要处理异常和错误,并进行适当的错误处理和回滚操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值