一,使用Python初始化2个表的数据
-
创建表 student 和 student2
use test; CREATE TABLE student(id int primary key auto_increment, name varchar(20), age int); CREATE TABLE student(id int primary key auto_increment, name varchar(20), sex varchar(10));
-
使用 Python 的
pymysql
库初始化这 2 张表的数据import random import pymysql if __name__ == '__main__': params = { 'host': '172.0.0.1', 'user': 'root', 'password': 'yourpassword', 'database': 'test' } conn = pymysql.Connect(**params) db_cursor = conn.cursor() # 初始化数据库的student表,表存储了名字和年龄 students = [] for i in range(10): name = f'name{i}' age = random.randint(16, 26) students.append((name, age)) db_cursor.executemany("INSERT INTO student(name, age) VALUES (%s, %s);", students) # 初始化数据库的student2表,表存储了名字和性别 students.clear() for i in range(5, 15): name = f'name{i}' sex = 'male' if random.randint(0, 1) else 'female' students.append((name, sex)) db_cursor.executemany("INSERT INTO student2(name, sex) VALUES (%s, %s);", students) conn.commit() db_cursor.close() conn.close()