2023.12.7 制作脚本快速生成数据库表和测试数据
建立数据库表
import random
from datetime import datetime, timedelta
import pymysql
# 创建数据库连接
conn = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
db='your_database_name',
charset='utf8mb4'
)
# 创建游标对象
cursor = conn.cursor()
# 生成测试数据
for _ in range(20):
name = "User" + str(random.randint(1, 100))
age = random.randint(18, 60)
gender = random.choice(["Male", "Female"])
hire_date = datetime.now() - timedelta(days=random.randint(0, 365))
salary = round(random.uniform(2000.0, 10000.0), 2)
insert_query = f"INSERT INTO employees (name, age, gender, hire_date, salary) VALUES ('{name}', {age}, '{gender}', '{hire_date.strftime('%Y-%m-%d')}', {salary})"
cursor.execute(insert_query)
# 提交更改到数据库
conn.commit()
# 关闭游标和连接
cursor.close()
conn.close()
自动生成测试数据,并导入数据库
import pymysql
from datetime import datetime
conn = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
db='your_database_name',
charset='utf8mb4'
)
# 创建游标对象
cursor = conn.cursor()
# 生成测试数据
for _ in range(20):
name = "User" + str(random.randint(1, 100))
age = random.randint(18, 60)
gender = random.choice(["Male", "Female"])
hire_date = datetime.now() - timedelta(days=random.randint(0, 365))
salary = round(random.uniform(2000.0, 10000.0), 2)
insert_query = f"INSERT INTO employees (name, age, gender, hire_date, salary) VALUES ('{name}', {age}, '{gender}', '{hire_date.strftime('%Y-%m-%d')}', {salary})"
cursor.execute(insert_query)
# 提交更改到数据库
conn.commit()
# 关闭游标和连接
cursor.close()
conn.close()