[toc]
数据库操作
1 实验类型
验证型,2学时,必选实验
2 实验目的
掌握sqlite数据库操作流程;熟悉sqlite3常见函数;
3 实验内容与要求
使用sqlite3实现学生表(学号, 姓名, 年龄), 课程表(编号, 课程名, 学分), 学生选课表(学号, 课程号, 成绩)的增删改查;
4 实验环境
Microsoft Edge/Chrome/Firefox
等浏览器,Visual Studio Code
,Python 3.4+
步骤
- 创建工作目录
学号
,最终目录结构如下(包含创建的各类文件):
建表
-
使用Sqlite Studio创建stu.db数据库
-
在stu.db中创建student表,参考代码如下:
create_student.py
import sqlite3
conn = sqlite3.connect("student.db")
print ("数据库打开成功")
c = conn.cursor()
c.execute('''CREATE TABLE Student
(No INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL
);''')
print ("数据表创建成功")
conn.commit()
conn.close()
- 完成课程表,选课表的操作
INSERT操作
- 使用execute函数实现记录的
INSERT
操作,如:
import sqlite3
conn = sqlite3.connect('student.db')
c = conn.cursor()
print ("数据库打开成功")
c.execute("INSERT INTO Student (No,NAME,AGE) \
VALUES (1, 'Paul', 32)")
c.execute("INSERT INTO Student (No,NAME,AGE) \
VALUES (2, 'Allen', 25)")
c.execute("INSERT INTO Student (No,NAME,AGE) \
VALUES (3, 'Teddy', 23)")
c.execute("INSERT INTO Student (No,NAME,AGE) \
VALUES (4, 'Mark', 25)")
conn.commit()
print ("数据插入成功")
conn.close()
- 完成课程表,选课表的对应操作
SELECT操作
- 使用execute函数实现记录的
SELECT
操作,如:
import sqlite3
conn = sqlite3.connect('student.db')
c = conn.cursor()
print ("数据库打开成功")
sql = "SELECT no, name, age from student"
cursor = c.execute(sql)
for row in cursor:
print("No = ", row[0])
print("Name = ", row[1])
print("Age = ", row[2], "\n")
print ("数据操作成功")
conn.close()
- 完成课程表,选课表的对应操作
UPDATE操作
- 使用execute函数实现记录的
UPDATE
操作,如:
import sqlite3
conn = sqlite3.connect('student.db')
c = conn.cursor()
print ("数据库打开成功")
c.execute("UPDATE Student set age = 23 where No=1")
conn.commit()
print("Total number of rows updated :", conn.total_changes)
cursor = conn.execute("SELECT no, name, age from Student")
for row in cursor:
print("No = ", row[0])
print("Name = ", row[1])
print("Age = ", row[2], "\n")
print ("数据操作成功")
conn.close()
- 完成课程表,选课表的对应操作
DELETE操作
- 使用execute函数实现记录的
DELETE
操作,如:
import sqlite3
conn = sqlite3.connect('student.db')
c = conn.cursor()
print ("数据库打开成功")
c.execute("DELETE FROM Student WHERE No=2;")
conn.commit()
print("Total number of rows deleted :", conn.total_changes)
cursor = conn.execute("SELECT No, Name, Age FROM Student")
for row in cursor:
print("No = ", row[0])
print("Name = ", row[1])
print("Age = ", row[2], "\n")
print ("数据操作成功")
conn.close()
- 完成课程表,选课表的对应操作