批量向一张表插入大量数据操作方法。
如,向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)
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倍速度以上。