pymysql 批量插入数据

前端之家收集整理的这篇文章主要介绍了pymysql 批量插入数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

批量向一张表插入大量数据操作方法

如,向tags表插入name

sql = 'INSERT INTO 表名 (字段名) VALUES (%s,%s,%s)'

在python中,sql语句中参数,一定要使用%s作为占位符号。在web开发中,可以避免sql注入,和减少开发中遇到莫名其妙的错误

准备代码

impor pyMysqL

conn = pyMysqL.connect(host='192.168.3.xxx',       user='root',       password='root',       db='xxx',       charset='utf8mb4',       cursorclass=pyMysqL.cursors.DictCursor)

使用pymsql 一般插入数据方法

param=[]
with conn.cursor() as cursor:
    for name in data:
        param.append([name])
    cursor.execute(sql, param)
    
conn.commit()

使用executemany命令

param=[]

for name in data:
    param.append([name])

try:
    with conn.cursor() as cursor:
        cursor.executemany(sql, param)
        conn.commit()   
except Exception as e:
	print e
	conn.rollback()	

建议使用executemany,因为使用executemany速度是使用execute大概10倍速度以上。

猜你在找的MySQL相关文章