2.使用 Python 操作 MySQL 数据库,创建一个管理学生信息的数据库,并把表 1 学生表中的数据填充到数据库中。 (15 分) 表 1 学生表 学号 姓名 性别 年龄 95001 王小明 男 21 95002 张梅梅 女 20
时间: 2024-10-19 20:17:11 浏览: 39
在Python中使用MySQL数据库需要安装`pymysql`库。首先,确保已经安装了这个库,如果没有可以使用pip安装:
```bash
pip install pymysql
```
接下来,你可以按照以下步骤操作:
1. **连接到MySQL服务器**:
```python
import pymysql
# 连接数据库,替换为你的数据库配置
db_config = {
'host': 'localhost', # 数据库主机地址
'user': 'your_username', # 数据库用户名
'password': 'your_password', # 数据库密码
'database': 'student_db' # 数据库名
}
# 创建连接
connection = pymysql.connect(**db_config)
```
2. **创建表结构**:
```python
cursor = connection.cursor()
sql_create_table = """
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
student_id VARCHAR(6) NOT NULL,
name VARCHAR(20) NOT NULL,
gender CHAR(4),
age INT
);
"""
cursor.execute(sql_create_table)
connection.commit()
```
3. **填充数据**:
```python
# 定义插入数据的函数
def insert_student_data(student_id, name, gender, age):
sql_insert = f"INSERT INTO students (student_id, name, gender, age) VALUES (%s, %s, %s, %s)"
cursor.execute(sql_insert, (student_id, name, gender, age))
# 学生数据列表
students_list = [
('95001', '王小明', '男', 21),
('95002', '张梅梅', '女', 20),
]
# 插入数据
for data in students_list:
insert_student_data(*data)
connection.commit() # 提交事务
```
4. **关闭连接**:
```python
cursor.close()
connection.close()
```
完成以上步骤后,你就成功地创建了一个名为“students”的表并填充了给定的学生数据。
阅读全文
相关推荐


















