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


    最近想写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())

  • 相关阅读:
    vue开发chrome扩展,数据通过storage对象获取
    Vue手动集成less预编译器
    Google Translate寻找之旅
    Javascript Range对象的学习
    Javascript Promises学习
    SublimeText 建立构建Node js系统
    We're sorry but demo3 doesn't work properly without JavaScript enabled. Please enable it to continue.
    npm安装包出现UNMET DEPENDENCY报错
    (转载)命令行说明中格式 尖括号 中括号的含义
    Linux重启网卡服务Failed to start LSB: Bring up/down networking.
  • 原文地址:https://www.cnblogs.com/yoyoma0355/p/10598983.html
Copyright © 2020-2023  润新知