python 往mysql数据库中插入多条记录。

时间:2021-11-15 21:42:08

最近想写mysql库,用到insert into语句,如何一次性将多条记录插入库表中呢。

 

MySQLdb提供了两个执行语句的方法:一个是execute(),另一个是executemany()

 

execute(sql)

       可接受一条语句从而执行

 

executemany(templet,args)

       能同时执行多条语句,执行同样多的语解码器可比execute()快得多,强烈建议执行多条语句时使用executemany

       templet:sql模板字符串,

             例如: ‘insert into table(id,name) values(%s,%s)’

       args:模板字符串中的参数,是一个列表,列表中的每一个元素必须是元组!!!

             例如:[(1,'小明'),(2,'小红'),(3,'琦琦'),(4,'韩梅梅')]

 



#!/usr/bin/env python
# encoding: utf-8
import pymysql
from config.config import *
import datetime
def get_conn():
conn=pymysql.connect(host=HOST,port=PORT,user=USER,passwd=PASSWORD,db=DB,charset=CHARSET, cursorclass=pymysql.cursors.DictCursor)
return conn
def get_idlist():
datalist=[]
conn=get_conn()
try:
with conn.cursor() as cursor:
sql="select PAGE_CD,PAGE_NAME from sns_page where PAGE_ID in(%s,%s,%s)"%tuple(IDLIST)
print(sql)
cursor.execute(sql)
datalist=cursor.fetchall()
except Exception as e:
print(e.args)
finally:
conn.close()
return datalist
def save_data(dicts):
now=datetime.datetime.now()
conn=get_conn()
data=((now,dicts["PAGE_CD"],"FB","FANS_NUM",dicts["FANS_NUM"],now),(now,dicts["PAGE_CD"],"FB","FOLLOW_NUM",dicts["FOLLOW_NUM"],now))
try:
with conn.cursor() as cursor:
sql="insert into sns_insight_log(LOG_DATE,BIZ_ID,MEDIA_TYPE,ITEM_NAME,DEC_VALUE,UPD_DATE) values(%s,%s,%s,%s,%s,%s)"
cursor.executemany(sql,data)
conn.commit()
except:
conn.rollback()
finally:
conn.close()
if __name__=="__main__":
print(get_idlist())