标签:into exec not commit ofo hal author env odi
#!/usr/bin/python #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/15 22:46 # @Author : Kwan # @File : insert_db.py # @Software: PyCharm import sqlite3 import random import datetime # conn = sqlite3.connect('local.db') # # c = conn.cursor() # # c.execute("insert into system_cfg values(?,?,?)",(2,'test2',1)) # # conn.commit() # # conn.close() def make_date(): # def make_card_number(bits): # counter = bits # number_list = [] # while counter: # number_list.append(str(random.randrange(0, 10))) # counter -= 1 # return number_list number_list = [str(x) for x in range(0, 10)] card_number = '' card_number = card_number.join(tuple(random.choices(number_list,k=10))) # card_number = '' # card_number = card_number.join(tuple(make_card_number(10))) car_type = random.choice(('m','p')) localtime = datetime.date.isoformat(datetime.datetime.now()) data_title = ['card_number','car_type','localtime'] data_dict = dict.fromkeys(data_title) data_dict['card_number'] = card_number data_dict['car_type'] = car_type data_dict['localtime'] = localtime return data_dict def insert_data(list): conn = sqlite3.connect('test.db') c = conn.cursor() try: id = max(c.execute("select max(id) from monthly_card").fetchall()) max_id = int(id[0]) for data in list: card_number = data['card_number'] db_car_number = c.execute("select card_number from monthly_card").fetchall() if card_number in db_car_number: break else: car_type = data['car_type'] localtime = data['localtime'] max_id += 1 c.execute("insert into monthly_card values (?,?,?,?)", (max_id, card_number, car_type, localtime)) except sqlite3.OperationalError: sql = '''create table if not exists monthly_card (id int primary key not null, card_number text not null, car_type text not null, valid text not null);''' c.execute(sql) id = 0 for data in list: try: card_number = data['card_number'] db_car_number = c.execute("select card_number from monthly_card").fetchall() if card_number in db_car_number: break else: car_type = data['car_type'] localtime = data['localtime'] id += 1 c.execute("insert into monthly_card values (?,?,?,?)", (id, card_number, car_type, localtime)) except sqlite3.OperationalError: card_number = data['car_number'] car_type = data['car_type'] localtime = data['localtime'] id += 1 c.execute("insert into monthly_card values (?,?,?,?)", (id, card_number, car_type, localtime)) # print(type(id_1)) # id = id_1.fetchall() conn.commit() conn.close() # def select_data(): # conn = sqlite3.connect('test.db') # c = conn.cursor() # db_car_number = c.execute("select card_number") # test1 = make_date() # my_list = [] # my_list.append(test1) # insert_data(my_list) # print('OK') n = 500 my_list = [] while n: my_list.append(make_date()) n-=1 insert_data(my_list) print('OK')标签:into exec not commit ofo hal author env odi
原文地址:http://blog.51cto.com/1003227425/2131480