MySQL数据库批量写入python脚本

MySQL数据库批量写入python脚本

这是一个个人信息的数据库批量写入的脚本,随机生成的一些数据,如有变动,可以在代码上稍作修改即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import pymysql
import random
db = pymysql.connect(
user = "root",
password = "qwer",
host = "localhost",
database = "utf8"
)
cursor = db.cursor()
IDnumber_pre = "1010"
Phone_pre = "(86)1"
Country_pre = "CN"
Address_pre = "RM 1-10,THRD,HY District,WH"
randnum = ""
for i in range(100):
randnum += str(random.randint(0,9))
for i in range(1):
IDnumber = IDnumber_pre + ''.join(random.sample(randnum,14))
name = (''.join(random.sample("abcdefghijklmnopqrstuvwxyz",8))).title()
Phone = Phone_pre + ''.join(random.sample(randnum,10))
Country = random.choice(["CN", "US", "UK"])
Address = Address_pre
Email = ''.join(random.sample("abcdefghijklmnopqrstuvwxyz123456789" , random.randint(5,15))) + "@" + random.choice(["qq.com", "163.com", "wuhan.com"])
DataOfBirth = str(random.randint(1920,2020)) + "-" + str(random.randint(1,12)) + "-" + str(random.randint(1,28))
print(IDnumber, name, Phone, Country, Address, Email, DataOfBirth)
sql = "insert into PassengerInfo(IDNumber,Name,PhoneNumber,Country,Address,Email,DataOfbirth) value('%s','%s','%s','%s','%s','%s','%s')" % (IDnumber, name, Phone, Country, Address, Email, DataOfBirth)
try:
cursor.execute(sql)
except Exception as e:
print(e)
else:
print(sql)
db.commit()
cursor.close()
db.close()