pymysql连接MySQL数据库实现学生宿舍管理系统
时间: 2023-07-20 19:21:18 浏览: 113
Java+JSP+Mysql实现Web学生宿舍管理系统(含E-R图和SQL语句)
5星 · 资源好评率100%
好的,下面是一个简单的基于pymysql库连接MySQL实现学生宿舍管理系统的示例代码,供您参考:
```python
import pymysql
# 连接到数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='your_password', db='your_database')
# 创建游标对象
cursor = conn.cursor()
# 创建学生表
sql_create_student_table = """
CREATE TABLE IF NOT EXISTS student (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20),
age INT,
gender VARCHAR(10),
dormitory_id INT,
FOREIGN KEY (dormitory_id) REFERENCES dormitory(id)
)
"""
cursor.execute(sql_create_student_table)
# 创建宿舍表
sql_create_dormitory_table = """
CREATE TABLE IF NOT EXISTS dormitory (
id INT PRIMARY KEY AUTO_INCREMENT,
building VARCHAR(10),
room_number INT,
capacity INT
)
"""
cursor.execute(sql_create_dormitory_table)
# 插入宿舍数据
sql_insert_dormitory = """
INSERT INTO dormitory (building, room_number, capacity) VALUES
('A', 101, 4),
('A', 102, 4),
('A', 103, 4),
('B', 201, 6),
('B', 202, 6),
('B', 203, 6)
"""
cursor.execute(sql_insert_dormitory)
conn.commit()
# 插入学生数据
sql_insert_student = """
INSERT INTO student (name, age, gender, dormitory_id) VALUES
('张三', 18, '男', 1),
('李四', 19, '男', 1),
('王五', 20, '女', 2),
('赵六', 21, '男', 3),
('钱七', 22, '女', 4),
('孙八', 23, '男', 5)
"""
cursor.execute(sql_insert_student)
conn.commit()
# 查询学生信息
sql_select_student = """
SELECT student.name, student.age, student.gender, dormitory.building, dormitory.room_number
FROM student
JOIN dormitory ON student.dormitory_id = dormitory.id
"""
cursor.execute(sql_select_student)
results = cursor.fetchall()
# 打印结果
print("学生信息")
for row in results:
name = row[0]
age = row[1]
gender = row[2]
building = row[3]
room_number = row[4]
print(f"name: {name}, age: {age}, gender: {gender}, dormitory: {building}{room_number}")
# 关闭游标和连接
cursor.close()
conn.close()
```
以上代码中,首先创建了一个学生表和一个宿舍表,然后插入了一些宿舍数据和学生数据,最后查询了学生信息并打印了结果。需要注意的是,这只是一个简单的示例,实际的学生宿舍管理系统需要更加完善和复杂的功能,例如添加、删除、修改学生信息、宿舍信息,查询宿舍剩余床位等等。您可以根据自己的需求进行修改和完善。
希望这能对您有所帮助。如果您还有其他问题,欢迎随时提出。
阅读全文