python设计学生通讯录,可以添加、删除、修改、显示里面所有信息。要求使用数据库方法
时间: 2023-12-31 12:06:56 浏览: 67
好的,你可以使用Python内置的SQLite数据库来实现这个学生通讯录。下面是一个简单的实现步骤:
1. 导入SQLite模块
```python
import sqlite3
```
2. 连接数据库
```python
conn = sqlite3.connect('student.db')
```
3. 创建表格
```python
conn.execute('''
CREATE TABLE STUDENT
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
EMAIL TEXT NOT NULL);
''')
```
4. 添加学生信息
```python
def add_student(conn, id, name, age, email):
conn.execute("INSERT INTO STUDENT (ID, NAME, AGE, EMAIL) \
VALUES (?, ?, ?, ?)", (id, name, age, email))
conn.commit()
```
5. 删除学生信息
```python
def delete_student(conn, id):
conn.execute("DELETE from STUDENT where ID = ?", (id,))
conn.commit()
```
6. 修改学生信息
```python
def update_student(conn, id, name, age, email):
conn.execute("UPDATE STUDENT set NAME = ?, AGE = ?, EMAIL = ? where ID = ?", (name, age, email, id))
conn.commit()
```
7. 显示所有学生信息
```python
def show_all_students(conn):
cursor = conn.execute("SELECT ID, NAME, AGE, EMAIL from STUDENT")
for row in cursor:
print("ID = ", row[0])
print("NAME = ", row[1])
print("AGE = ", row[2])
print("EMAIL = ", row[3])
```
8. 关闭数据库连接
```python
conn.close()
```
这样,一个简单的学生通讯录就完成了。你可以根据自己的需求来修改和扩展这个程序。
阅读全文