pythonはmysqlテーブルに大量にデータを挿入することを実現し、テーブル1とテーブル2がフィールドを挿入する値が一致し(10ビットの数字)、テーブル2の別のフィールドが特定の値(ファイル)を挿入する必要がある.

6780 ワード

#python         mysql  ,    1  2          (  10    ),  2             (    )

import pymysql
import random

db = pymysql.connect(
    host='XXX',
    port=  ,
    user='   ',
    password='  ',
    database='  ',
    charset='utf8'
)

cursor = db.cursor()
#        ,    a ;           
file = open(r"    ","r",encoding='utf-8')
a = file.read().splitlines()

for i in range(1):
    for j in a:
        #      
        k = random.randint(0000000000,9999999999)
        #rjust   ,  10    0  
        k_format = str(k).rjust(10,'0')
        #      ,     
        g = random.randint(0,299999)
        #  g     ,k_format         10   ,str(j)         
        sql_1 = """
        INSERT INTO table_a VALUES ({0},\'{1}\', '  ', 
         '  ', '  ', NULL, 0, 50, 0, '2020-7-3', 
         '2021-7-3', '2020-7-3 10:50:43', '2020-7-3 10:50:43', NULL, NULL, NULL, NULL);
        """.format(g,k_format)
        sql_2 = "INSERT INTO table_b VALUES ({0},\'{1}\',\'{2}\', 30, 0, 0, '2020-7-10 16:20:25', '2020-7-16 15:24:47');".format(g,str(j),k_format)
        print(sql_1)
        print(sql_2)
        #       ,     sql     ,            
        try:
            #    sql
            cursor.execute(sql_1)
            db.commit()
            cursor.execute(sql_2)
            db.commit()
        except:
            pass

#  cursor、db、file
cursor.close()
db.close()
file.close()