帮我写一个mysql数据库项目
时间: 2023-08-28 19:08:51 浏览: 31
好的,下面是一个简单的 MySQL 数据库项目:
该项目旨在创建一个简单的学生管理系统,可以执行以下操作:
1. 添加学生信息
2. 更新学生信息
3. 删除学生信息
4. 显示所有学生信息
该系统需要以下表格:
1. 学生表格:包含学生的 ID,姓名,年龄,性别和地址信息。
2. 成绩表格:包含学生的 ID 和成绩信息。
以下是创建这些表格的 SQL 语句:
```
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
age INT NOT NULL,
gender VARCHAR(10) NOT NULL,
address VARCHAR(100) NOT NULL
);
CREATE TABLE scores (
id INT PRIMARY KEY AUTO_INCREMENT,
student_id INT NOT NULL,
subject VARCHAR(50) NOT NULL,
score INT NOT NULL,
FOREIGN KEY (student_id) REFERENCES students(id)
);
```
接下来,您可以使用以下代码创建一个简单的 Python 应用程序,以便用户可以与该系统交互:
```python
import mysql.connector
# 连接到数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="students"
)
# 创建游标对象
mycursor = mydb.cursor()
# 添加学生信息
def add_student(name, age, gender, address):
sql = "INSERT INTO students (name, age, gender, address) VALUES (%s, %s, %s, %s)"
val = (name, age, gender, address)
mycursor.execute(sql, val)
mydb.commit()
print("Student added successfully")
# 更新学生信息
def update_student(id, name, age, gender, address):
sql = "UPDATE students SET name = %s, age = %s, gender = %s, address = %s WHERE id = %s"
val = (name, age, gender, address, id)
mycursor.execute(sql, val)
mydb.commit()
print("Student updated successfully")
# 删除学生信息
def delete_student(id):
sql = "DELETE FROM students WHERE id = %s"
val = (id,)
mycursor.execute(sql, val)
mydb.commit()
print("Student deleted successfully")
# 显示所有学生信息
def show_students():
mycursor.execute("SELECT * FROM students")
result = mycursor.fetchall()
for row in result:
print(row)
# 主程序
while True:
print("1. Add student")
print("2. Update student")
print("3. Delete student")
print("4. Show all students")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
name = input("Enter student name: ")
age = input("Enter student age: ")
gender = input("Enter student gender: ")
address = input("Enter student address: ")
add_student(name, age, gender, address)
elif choice == '2':
id = input("Enter student ID: ")
name = input("Enter new name: ")
age = input("Enter new age: ")
gender = input("Enter new gender: ")
address = input("Enter new address: ")
update_student(id, name, age, gender, address)
elif choice == '3':
id = input("Enter student ID: ")
delete_student(id)
elif choice == '4':
show_students()
elif choice == '5':
break
else:
print("Invalid choice")
```
请注意,这只是一个简单的 MySQL 数据库项目示例,您可以根据需要进行修改和扩展。
阅读全文