批量向mysql中插入数据
test.py
import pymysql
from faker import Faker
import random
fakers = Faker('zh_CN')
connect = pymysql.connect(host='test.mysql.rds.aliyuncs.com',
user='testdba',
password='test',
db='data',
charset='utf8')
cur = connect.cursor()
def random_sex():
num = random.randint(1, 2)
if num == 1:
return '男'
else:
return '女'
i = 1
while i < 150:
data = {
'name': fakers.name(),
'sex': random_sex(),
'age': random.randint(18, 70),
'addr': fakers.address() + fakers.building_number(),
'email': fakers.email(),
'tel': fakers.phone_number(),
'ip': fakers.ipv4(),
'url': fakers.url(schemes=None),
'describe': fakers.text(max_nb_chars=200, ext_word_list=None) + "机密"
}
sql = f"INSERT INTO `data`.`test` (`name`, `age`, `addr`, `email`, `tel`, `ip`, `url`, `describe`, `sex`) VALUES " \
f"('{data['name']}', '{data['age']}', '{data['addr']}', '{data['email']}', '{data['tel']}', '{data['ip']}', " \
f"'{data['url']}', '{data['describe']}', '{data['sex']}');"
cur.execute(sql)
connect.commit()
i += 1