python3批量向Mysql中插入數據

python3批量向Mysql中插入數據

#!/usr/bin/python3  
# -*- coding: utf-8 -*-
# @Time    : 2019/9/26 0026 19:57
# @Author  : P.D
# @Site    : python3批量向Mysql中插入數據
# @File    : test.py
import pymysql
import random

db = pymysql.connect("localhost", "root", "123456", 'blog')
cursor = db.cursor()
data = list()
for i in range(10):
    title_list = ["python", "flask", "Django"]
    body_list = ["this is python", "this is flask", "this is Django"]
    value = (random.choice(title_list), random.choice(body_list))
    data.append(value)


def insert_data():
    sql = "insert into blog(title, body) values (%s, %s)"
    try:
        cursor.executemany(sql, data)
        db.commit()
        print("insert success")
    except:
        db.rollback()


if __name__ == '__main__':
    insert_data()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章