zoukankan      html  css  js  c++  java
  • 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()
    

      

  • 相关阅读:
    迭代器、生成器
    函数(函数基础、装饰器、递归、匿名函数)
    文件处理
    python对象、引用
    字符编码
    流程控制if、while、for
    编程与编程语言
    Java源码阅读(五)—— AbstractQueuedSynchronizer
    Java并发编程(二) —— volatile
    Java源码阅读(七)—— ReentrantReadWriteLock
  • 原文地址:https://www.cnblogs.com/dmtz/p/14863439.html
Copyright © 2011-2022 走看看