python向数据库批量插入数据每条数据相隔5分钟

 

 上代码

#coding=utf-8
import pymysql
import datetime
import time
import random


#获取当天日期格式化输出
date1 = datetime.datetime.now().strftime("%Y%m%d")
# 获取当天0点的时间戳
today_stamp=int(time.mktime(datetime.date.today().timetuple()))
# 获取当前的创建时间格式化输出
time1 = "'"+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"'"

class Insert():
    #初始化属性
    def __init__(self):
        self.host = "ip"
        self.port = 3306
        self.user = "root"
        self.passwd = "root"
        self.charset = "utf8mb4"
        self.db = "数据库名"
        self.table = "表名"
       
        self.cross_code = "'"+"1111111111111111"+"'"     
        self.branch_code = "'"+"2222222222"+"'"  
    #连接数据库
    def cursor(self):
        connection =pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            passwd=self.passwd,
            db=self.db,
            cursorclass=pymysql.cursors.DictCursor,
            autocommit=True
           )
        return  connection


    def query(self):
        """获取mysql中最后一个id,并返回"""
        try:
            sql = f"SELECT id from {self.table} ORDER BY id desc LIMIT 1;"
            cursor = self.cursor().cursor()
            cursor.execute(sql)
            results =cursor.fetchall()
            if not  results :
                    return 0
            else:
                id = results[0]['id']
                return  id


        except IndentationError as error:
            print(error)
        self.cursor().close()

    """往数据库中批量插入数据"""
    def Linesinsert(self):
        """一天有1440分钟,共288个5分钟"""
        for i in range(0, 10):
            j = today_stamp * 1000 + (i*300000)
            """从当天0点开始的时间戳转为时间格式(如10整:100000)"""
            otherStyleTime = int(time.strftime("%H%M%S", time.localtime(j/1000)))
            ram = random.random()
            print("第%d条数据"%i)
            try:
                # 创建MySQL连接、并且获取游标
                cursor =  self.cursor().cursor()
                #sql命令
                sql =f"INSERT INTO `aitpm_nanning`.{self.table}(`id`, `begin`, `created_date`, `date`, `end`, `period`, `time`, `value`, `branch_code`, `cross_code`, `dimension`, `turn`, `sum_period`, `sum_value`)" \
                     f" VALUES ({self.query()+1}, {j}, {time1}, {date1}, {j+300000}, 'P5', {otherStyleTime}, {ram}, {self.branch_code}, {self.cross_code}, 'BRANCH', NULL, 1, {ram});"
                cursor.execute(sql)

            except Exception as e :
                print(e)
            finally:
                #关闭游标
                cursor.close()
                #提交
                self.cursor().commit()
                #关闭数据库连接
                self.cursor().close()
                print(sql)


if __name__ == '__main__':
    a = Insert()
    a.Linesinsert()
    a.query()








你可能感兴趣的:(python,数据库,java)