Python 生成千万条数据,并且插入到数据库中

 1 import random
 2 import sqlite3
 3 
 4 
 5 def draw_double_color_ball():
 6     # 红球编号列表
 7     red_balls = list(range(1, 34))  # 编号从1到33
 8     # 蓝球编号列表
 9     blue_balls = list(range(1, 17))  # 编号从1到16
10 
11     # 从红球中随机抽取6个不重复的号码
12     drawn_red_balls = random.sample(red_balls, 6)
13     drawn_red_balls.sort()
14     # 从蓝球中随机抽取1个不重复的号码
15     drawn_blue_ball = random.choice(blue_balls)
16 
17     # 返回抽取结果
18     return drawn_red_balls, drawn_blue_ball
19 
20 
21 conn = sqlite3.connect('ball.db')
22 cur = conn.cursor()
23 with open('demo.txt', 'r', encoding='utf-8') as f:
24     for line in f:
25         # 获取到索引
26         str_index = line.find("[")
27         str_01 = line[:str_index]
28         print("~~~~~~~~~>>>当前插入条数: ", str_01)
29 
30         # 获取数据列表(6)
31         str_end = line.find("]")
32         str_02 = line[str_index:str_end]
33         str_03 = str_02[1:]
34         # print("~~~~~~~~~>>>真实数据源: ", str_03)
35 
36         # 获取最后一位数据
37         str_05 = line.find("]")
38         str_06 = line[str_05:]
39         str_07 = str_06[1:]
40         str_last = str_07.strip()
41         # print("~~~~~~~~~>>>获取最后一位数据: ", str_last)
42 
43         # 对获取的真实数据进行分割排序
44         real = str_03.split(",")
45         real.sort(key=int)
46         # print("~~~~~~~~~>>>分割排序后的列表: ", real)
47 
48         cur.execute(
49             "insert into double_ball(read_ball_1,read_ball_2,read_ball_3,read_ball_4,read_ball_5,read_ball_6,blue_ball) values(?,?,?,?,?,?,?)",
50             (real[0], real[1], real[2], real[3], real[4], real[5], str_last))
51         conn.commit()
52 conn.close()
53 print("~~~~~~~~~~~~~~~>>>>执行完成<<<<~~~~~~~~~~~~~~~")

 

posted @ 2024-05-23 13:07  逍遥散人95  阅读(65)  评论(0编辑  收藏  举报