python3-数据库插入数据(pymysql)

#!/usr/bin/python

import pymysql
import  time
import  random

host = "host"
user = "user"
password = "password"
db = "dbname"

transit_depot_no = "xxx"

# 打开数据库连接
db = pymysql.connect(host=host, user=user, password=password, db=db, charset="utf8")

for i in range(0,10):
    a = random.randint(0, 1800)
    d = random.randint(7200,14400)
    warn_time = int(time.time()) + a
    end_time = int(time.time()) + 86400
    actual_depart_tm = int(time.time()) - d
    actual_arrive_tm = warn_time - 1800
    nowArray = time.localtime(warn_time)
    endArray = time.localtime(end_time)
    actual_depart_tmArray = time.localtime(actual_depart_tm)
    actual_arrive_tmArray = time.localtime(actual_arrive_tm)
    newtime = (time.strftime("%Y-%m-%d %H:%M:%S", nowArray))
    newendtime = (time.strftime("%Y-%m-%d %H:%M:%S", endArray))
    localtimenow = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    newactual_depart_tm = time.strftime("%Y-%m-%d %H:%M:%S", actual_depart_tmArray)
    newactual_arrive_tm = time.strftime("%Y-%m-%d %H:%M:%S", actual_arrive_tmArray)

    # SQL 插入语句
    sql1 = """这里是sql语句""" % (参数化1,参数化2)

    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    try:
        # 执行sql语句
        cursor.execute(sql1)
        #提交到数据库执行
        db.commit()
    except:
        # 如果发生错误则回滚
        db.rollback()

# 关闭数据库连接
db.close()

  

posted on 2021-06-08 16:38  lbxx  阅读(321)  评论(0编辑  收藏  举报

导航