测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A29407. 学生数据库设计一个SQLite数据库应用,实现以下功能:创建一个名为students的表,该表具有id(主键,自增)、name、age和grade四个字段。①插入5条学生记录。②修改一个学生的年龄③删除一个学生记录。④查询所有学生的信息。请根据要求,补全代码。(本题无需运行通过,写入代码即可)import sqlite3#连接到SQLite数据库(如果数据库不存在,则会创建一个新的数据库)con…

填空题 困难

题目描述

学生数据库

设计一个SQLite数据库应用,实现以下功能:

创建一个名为students的表,该表具有id(主键,自增)、name、age和grade四个字段。

①插入5条学生记录。

②修改一个学生的年龄

③删除一个学生记录。

④查询所有学生的信息。

请根据要求,补全代码。(本题无需运行通过,写入代码即可)


import sqlite3

#连接到SQLite数据库(如果数据库不存在,则会创建一个新的数据库)

conn=sqlite3.connect('students.db')

cursor=_______①_______

# 创建students表

cursorexecute('''CREATE TABLE IF NOT EXISTS students (

  id INTEGER PRIMARY KEY AUTOINCREMENT,

  name TEXT NOT NULL,

  age INTEGER,

  grade TEXT)

''')


# 插入5条学生记录

students =[

  ('Alice', 20,'A’),

  ('Bob', 22,'B’),

  ('Charlie', 19,'c'),

  ('David', 21, 'A'),

  ('Eva', 23,'B’)

  ]

cursor.executemany('''INSERT INTO students (name, age, grade) VALUES (?,?,?)

''',_____②______)

#修改一个学生的年龄(例如修改id为2的学生的年龄为24)

cursor.execute("UPDATE students SET age=24 WHERE id=2")

#删除一个学生记录(例如删除id为3的学生)

cursor.execute("DELETE FROM students WHERE id=3")

_____③______

#查询所有学生信息

cursor.execute('SELECT*FROM students')

print("所有学生信息:")

for row in_____④______

    print(row)

#关闭数据库连接

conn.close()

参考答案

import sqlite3 #连接到SQLite数据库(如果数据库不存在,则会创建一个新的数据库) conn=sqlite3.connect('students.db') cursor=conn.cursor() # 创建students表 cursorexecute('''CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, grade TEXT) ''') # 插入5条学生记录 students =[ ('Alice', 20,'A’), ('Bob', 22,'B’), ('Charlie', 19,'c'), ('David', 21, 'A'), ('Eva', 23,'B’) ] cursor.executemany('''INSERT INTO students (name, age, grade) VALUES (?,?,?) ''',students) #修改一个学生的年龄(例如修改id为2的学生的年龄为24) cursor.execute("UPDATE students SET age=24 WHERE id=2") #删除一个学生记录(例如删除id为3的学生) cursor.execute("DELETE FROM students WHERE id=3") conn,commit() #查询所有学生信息 cursor.execute('SELECT*FROM students') print("所有学生信息:") for row in cursor.fetchall(); print(row) #关闭数据库连接 conn.close()
上一题 下一题