Skip to content

[toc]

数据库操作

1 实验类型

验证型,2学时,必选实验

2 实验目的

掌握sqlite数据库操作流程;熟悉sqlite3常见函数;

3 实验内容与要求

使用sqlite3实现学生表(学号, 姓名, 年龄), 课程表(编号, 课程名, 学分), 学生选课表(学号, 课程号, 成绩)的增删改查;

4 实验环境

Microsoft Edge/Chrome/Firefox等浏览器,Visual Studio CodePython 3.4+

步骤

  1. 创建工作目录学号,最终目录结构如下(包含创建的各类文件):
学号:.
    create_student.py
    delete.py
    insert.py
    select.py
    student.db
    student.py
    update.py

建表

  1. 使用Sqlite Studio创建stu.db数据库

  2. 在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()
  1. 完成课程表,选课表的操作

INSERT操作

  1. 使用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()
  1. 完成课程表,选课表的对应操作

SELECT操作

  1. 使用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()
  1. 完成课程表,选课表的对应操作

UPDATE操作

  1. 使用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()
  1. 完成课程表,选课表的对应操作

DELETE操作

  1. 使用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()
  1. 完成课程表,选课表的对应操作