import pymysql
import faker
from datetime import datetime
# 连接MySQL数据库
conn = pymysql.connect(
host='localhost',
user='root',
password='root',
database='bigdata',
charset='utf8mb4'
)
# 创建一个游标对象
cursor = conn.cursor()
# 使用Faker库生成模拟数据
fake = faker.Faker()
# 生成并插入200条数据
for _ in range(200):
s_name = fake.name()
s_sex = fake.random_element(elements=('Male', 'Female'))
s_birthday = fake.date_of_birth().strftime('%Y-%m-%d')
s_addr = fake.address()[:50]
s_cid = fake.random_int(min=1, max=10) # 假设s_cid是1到10之间的随机整数
# 构造插入语句
insert_query = f"INSERT INTO tb_student (s_name, s_sex, s_birthday, s_addr, s_cid) " \
f"VALUES ('{s_name}', '{s_sex}', '{s_birthday}', '{s_addr}', {s_cid});"
# 执行插入语句
cursor.execute(insert_query)
# 提交事务
conn.commit()
# 关闭连接
cursor.close()
conn.close()
Python批量模拟Mysql数据
最新推荐文章于 2024-04-13 18:37:41 发布