简答题 偏难
#6111

创建学生库 使用Python的sqlite3库完成以下问题。 (1)创建一个名为students的数据库; (2)在这个数据库中,创建一个名为students_…

创建学生库

使用Python的sqlite3库完成以下问题。

(1)创建一个名为students的数据库;

(2)在这个数据库中,创建一个名为students_table的表,包含以下字段:id(主键),name(学生的名字),age(学生的年龄),grade(学生的年级);

(3)向students_table中插入至少5个学生的数据;

(4)查询年龄大于18岁的所有学生,并打印结果;

(5)将名字为"Alice"的学生的年龄增加1岁;

(6)删除名字为"Bob"的学生。

(本题无需运行通过,写入代码即可)

import sqlite3
conn = sqlite3.connect('        ①        ')
cursor = conn.cursor()
cursor.execute('''        ②         students_table(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,age INTEGER,grade TEXT)''')
students = [ ('Alice', 17, '10th'), ('Bob', 18, '11th'), ('Charlie', 16, '10th'),  ('David', 19, '12th'),('Eve', 17, '11th')]
cursor.executemany('''INSERT INTO students_table (name, age, grade) VALUES (?, ?, ?)''', students)
conn.commit()
cursor.execute('SELECT * FROM students_table         ③        ')
print("年龄大于18岁的学生:")
print(cursor.        ④        )
cursor.execute('UPDATE students_table SET age = age + 1 WHERE name = "Alice"')
cursor.execute('DELETE FROM students_table WHERE name = "Bob"')
conn.commit()
conn.close()
未登录也能判分,登录后才会记录
答案与解析
正确答案:<pre class="brush:python;toolbar:false">import sqlite3 conn = sqlite3.connect('students.db') cursor = conn.cursor() cursor.execute('''CREATE TABLE students_table(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,age INTEGER,grade TEXT)''') students = [ ('Alice', 17, '10th'), ('Bob', 18, '11th'), ('Charlie', 16, '10th'),  ('David', 19, '12th'),('Eve', 17, '11th')] cursor.executemany('''INSERT INTO students_table (name, age, grade) VALUES (?, ?, ?)''', students) conn.commit() cursor.execute('SELECT * FROM students_table WHERE age &gt; 18') print("年龄大于18岁的学生:") print(cursor.fetchall()) cursor.execute('UPDATE students_table SET age = age + 1 WHERE name = "Alice"') cursor.execute('DELETE FROM students_table WHERE name = "Bob"') conn.commit() conn.close()</pre>
解析

评分标准:

(1)students.db 或等效答案;(2分)

(2)CREATE TABLE 或等效答案; (2分)

(3)WHERE age > 18 或等效答案;(3分)

(4)fetchall() 或等效答案。(3分)