mysql学生管理系统简单代码
时间: 2024-03-31 17:31:14 浏览: 10
当然可以!下面是一个简单的MySQL学生管理系统的代码示例:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="students"
)
# 创建学生表
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)")
# 插入学生数据
sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
val = ("John", 20)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
# 查询学生数据
mycursor.execute("SELECT * FROM students")
result = mycursor.fetchall()
for row in result:
print(row)
# 更新学生数据
sql = "UPDATE students SET age = %s WHERE name = %s"
val = (21, "John")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) updated.")
# 删除学生数据
sql = "DELETE FROM students WHERE name = %s"
val = ("John",)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted.")
# 关闭数据库连接
mydb.close()
```
这段代码使用了Python的`mysql.connector`库来连接MySQL数据库,并进行学生信息的增删改查操作。你需要将`yourusername`和`yourpassword`替换为你自己的MySQL用户名和密码,同时确保已经创建了名为`students`的数据库。