编程要求 打开右侧命令行窗口,启动 MySQL 服务,创建数据库 spark,并在该库中创建表 student,其字段及数据类型如下: 字段名 数据类型 备注 id int(4) 学号 name char(20) 姓名 gender char(4) 性别 age int(4) 年龄 创建完成后,在 student 表中添加如下两条数据: 1,'Xueqian','F',23 2,'Weiliang','M',24 打开右侧代码文件窗口,在 Begin 至 End 区域补充代码,使用 Python 语言编写程序读取 MySQL 数据中 spark.student 表的数据并输出,输出示例如下: +---+--------+------+---+ | id| name|gender|age| +---+--------+------+---+ | 1| Xueqian| F| 23| | 2|Weiliang| M| 24| +---+--------+------+---+ MySQL 数据库连接信息 账号: root 密码:123123 地址:127.0.0.1 端口:3306
时间: 2025-06-30 17:17:00 浏览: 16
### 使用 Python 连接 MySQL 并完成指定操作
以下是实现连接 MySQL 数据库、创建数据库 `spark` 和表 `student`(包含字段 `id`, `name`, `gender`, `age`),插入两条记录并读取输出的完整代码示例:
```python
import pymysql
# 配置字典用于管理连接参数
config = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': '123123',
'charset': 'utf8mb4',
'cursorclass': pymysql.cursors.DictCursor,
}
# 连接到 MySQL
connection = pymysql.connect(**config)
try:
with connection.cursor() as cursor:
# 创建数据库 spark
cursor.execute("CREATE DATABASE IF NOT EXISTS spark")
print("Database 'spark' created successfully.")
# 重新连接到新创建的数据库
config['db'] = 'spark'
connection = pymysql.connect(**config)
with connection.cursor() as cursor:
# 创建 student 表
create_table_sql = """
CREATE TABLE IF NOT EXISTS student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
gender ENUM('male', 'female') NOT NULL,
age INT NOT NULL
)
"""
cursor.execute(create_table_sql)
print("Table 'student' created successfully.")
# 插入两条记录
insert_sql = "INSERT INTO student (name, gender, age) VALUES (%s, %s, %s)"
data_to_insert = [
('Alice', 'female', 22),
('Bob', 'male', 24)
]
cursor.executemany(insert_sql, data_to_insert)
connection.commit()
print("Data inserted successfully.")
# 查询并输出表中的数据
select_sql = "SELECT * FROM student"
cursor.execute(select_sql)
results = cursor.fetchall()
for row in results:
print(f"ID: {row['id']}, Name: {row['name']}, Gender: {row['gender']}, Age: {row['age']}")
finally:
connection.close()
```
#### 代码说明
- **连接配置**:通过字典 `config` 管理连接参数,确保代码优雅且易于维护[^1]。
- **数据库创建**:使用 SQL 语句 `CREATE DATABASE IF NOT EXISTS spark` 创建名为 `spark` 的数据库。
- **表创建**:定义 `student` 表结构,包括字段 `id`, `name`, `gender`, `age`,其中 `id` 是主键并自动递增[^1]。
- **数据插入**:使用 `INSERT INTO` 语句插入两条记录,并通过 `executemany` 方法批量执行插入操作。
- **数据查询与输出**:通过 `SELECT * FROM student` 查询表中所有数据,并以字典形式逐行输出。
#### 注意事项
- 确保 MySQL 服务已启动,并且 root 用户具有相应权限。
- 如果密码或端口有变动,请根据实际情况修改 `config` 字典中的值。
- 在生产环境中,建议避免使用 root 用户连接数据库,而是创建专用用户并授予最小权限。
阅读全文