一、安装模块
cmd进入DOS界面,执行以下命令安装:
pip install PyMySQL
二、连接数据库并循环插入数据
- 连接数据库
import pymysql #导入模块
from time import time,sleep
import datetime
db = pymysql.connect("localhost", "root", "123456", "库名") #本机数据库连接
#远程连接数据库
db = pymysql.connect(
host='192.168.100.110',
port=3306,
user='root',
passwd='123456',
db ='库名',
charset='utf8'
)
#使用cursor()方法获取操作游标
cursor = db.cursor()
- 循环插入数据
for i in range(10): #循环10次
i = i + 1
Age = i + 1
CreateDate = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') #获取当前日期时间
sleep(1) #执行语句等待1秒
sql = """INSERT INTO flow (`Age`,`CreateDate`,`UserLogID`)
VALUES (\'{0}\',\'{1}\',\'12f0d408\');""".format(Age,CreateDate)
print(sql) #查看SQL语句是否正确
try:
cursor.execute(sql) #执行sql语句
db.commit() #COMMIT命令用于把事务所做的修改保存到数据库
print('新增'+str(i)+"数据")
except:
db.rollback() #发生错误时回滚
print("数据添加失败")
cursor.close() #关闭游标
db.close() #关闭数据库连接