写一个python MySQL 学生管理系统
时间: 2023-11-30 22:59:25 浏览: 30
好的,为您介绍一下基本的实现思路。
1. 连接数据库
使用Python内置的MySQLdb模块连接MySQL数据库。
```python
import MySQLdb
db = MySQLdb.connect("localhost", "用户名", "密码", "数据库名", charset="utf8")
cursor = db.cursor()
```
2. 创建表格
创建名为students的表格来存储学生信息。
```python
create_table_sql = '''
create table students(
id int not null auto_increment,
name varchar(20) not null,
gender varchar(10) not null,
age int not null,
primary key(id)
)CHARSET=utf8
'''
cursor.execute(create_table_sql)
```
3. 插入数据
插入学生信息到表格中。
```python
insert_student_sql = '''
insert into students(name, gender, age)
values (%s, %s, %s)
'''
name = '张三'
gender = '男'
age = 18
cursor.execute(insert_student_sql, (name, gender, age))
db.commit()
```
4. 查询数据
查询学生信息。
```python
select_student_sql = '''
select * from students
'''
cursor.execute(select_student_sql)
result = cursor.fetchall()
for row in result:
id = row[0]
name = row[1]
gender = row[2]
age = row[3]
print(id, name, gender, age)
```
5. 更新数据
更新学生信息。
```python
update_student_sql = '''
update students set age = 20 where name = '张三'
'''
cursor.execute(update_student_sql)
db.commit()
```
6. 删除数据
删除学生信息。
```python
delete_student_sql = '''
delete from students where name = '张三'
'''
cursor.execute(delete_student_sql)
db.commit()
```
以上就是一个简单的Python MySQL学生管理系统的实现。