使用python写一个造数据脚本,对应库为mysql
时间: 2024-02-03 19:11:21 浏览: 20
好的,可以使用Python中的random库和MySQL-Connector库来实现。下面是一个简单的例子:
```python
import random
import mysql.connector
# 连接数据库
db = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
# 创建游标
cursor = db.cursor()
# 生成随机数据
names = ['Alice', 'Bob', 'Charlie', 'David', 'Emma', 'Frank', 'Grace', 'Henry', 'Isabella', 'Jack']
ages = [18, 20, 22, 24, 26, 28, 30]
genders = ['M', 'F']
salaries = [1000, 2000, 3000, 4000, 5000]
# 插入数据
for i in range(10):
name = random.choice(names)
age = random.choice(ages)
gender = random.choice(genders)
salary = random.choice(salaries)
sql = "INSERT INTO employees (name, age, gender, salary) VALUES (%s, %s, %s, %s)"
val = (name, age, gender, salary)
cursor.execute(sql, val)
# 提交更改
db.commit()
# 关闭连接
db.close()
```
以上代码会随机生成10条员工数据,并将它们插入到名为"employees"的MySQL表中,该表必须先在数据库中创建好。注意,在实际使用中,我们可能需要更多的字段和更复杂的逻辑来生成数据。