你能给我一个python+mysql的学生管理实例吗
时间: 2023-06-24 21:05:28 浏览: 59
当然可以!以下是一个简单的Python+MySQL学生管理系统实例。
首先,你需要安装MySQL和Python的MySQL连接器。你可以使用以下命令在Ubuntu上安装:
```
sudo apt-get install mysql-server
pip install mysql-connector-python
```
接下来,创建一个名为“students”的数据库,并在其中创建一个名为“student_info”的表。以下是表的结构:
```sql
CREATE TABLE student_info (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT,
gender VARCHAR(10),
major VARCHAR(255)
);
```
接下来,你可以使用以下Python代码连接到数据库,并添加、删除、更新和查询学生信息。
```python
import mysql.connector
# Connect to the database
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="students"
)
# Add a new student
def add_student(name, age, gender, major):
cursor = db.cursor()
sql = "INSERT INTO student_info (name, age, gender, major) VALUES (%s, %s, %s, %s)"
values = (name, age, gender, major)
cursor.execute(sql, values)
db.commit()
print(cursor.rowcount, "record inserted.")
# Delete a student by ID
def delete_student(id):
cursor = db.cursor()
sql = "DELETE FROM student_info WHERE id = %s"
value = (id,)
cursor.execute(sql, value)
db.commit()
print(cursor.rowcount, "record(s) deleted.")
# Update a student by ID
def update_student(id, name, age, gender, major):
cursor = db.cursor()
sql = "UPDATE student_info SET name = %s, age = %s, gender = %s, major = %s WHERE id = %s"
values = (name, age, gender, major, id)
cursor.execute(sql, values)
db.commit()
print(cursor.rowcount, "record(s) updated.")
# Get all students
def get_students():
cursor = db.cursor()
cursor.execute("SELECT * FROM student_info")
rows = cursor.fetchall()
for row in rows:
print(row)
# Get a student by ID
def get_student(id):
cursor = db.cursor()
sql = "SELECT * FROM student_info WHERE id = %s"
value = (id,)
cursor.execute(sql, value)
row = cursor.fetchone()
if row:
print(row)
else:
print("No record found.")
# Add a few sample students
add_student("John Doe", 20, "Male", "Computer Science")
add_student("Jane Smith", 22, "Female", "Business")
add_student("Bob Johnson", 19, "Male", "Engineering")
# Get all students
get_students()
# Update a student
update_student(2, "Jane Doe", 23, "Female", "Marketing")
# Get a student by ID
get_student(1)
# Delete a student
delete_student(3)
# Get all students again
get_students()
```
这只是一个简单的示例,你可以根据自己的需要进行修改和扩展。