pymysql 常用操作[Python常见问题]

 

批量插入

import pymysql


def insert_to_mysql(to_db_list):
    mysql_db = pymysql.connect(host="HOST_IP", port=3306, user="username", password="password",
                               database="db", charset="utf8")
    cursor = mysql_db.cursor()
    sql = "INSERT INTO `your_db`.`your_table`(`colum1`, `colum2`, `colum3`) VALUES (%s,%s,%s)"

    try:
        # cursor.execute()
        cursor.executemany(sql, to_db_list)  # 批量插入
        
        effect_rows = cursor.rowcount
        
        mysql_db.commit()
        cursor.close()
        print("数据库添加成功,插入 {}条数据".format(effect_rows))
        return effect_rows
    except Exception as e:
        mysql_db.rollback()
        print("数据库执行失败")
        print(e)
        return 0

my_list = []
my_list.append(("v1", "v2", "v3"))

cnt = insert_to_mysql(my_list)
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » pymysql 常用操作