第12396题 程序题
补全Python操作SQLite数据库的代码,完成指定数据库操作任务

学生数据库操作编程题

编写Python程序操作SQLite数据库,并读出表中的数据,具体要求如下:

  1. 打开数据库连接;
  2. 清除已存在的表students
  3. 创建一个名为students的表;
  4. 向新表插入测试数据;
  5. 读取students表中的所有数据并输出。

本题无需运行通过,只需写入补全后的代码即可。

import sqlite3
# 打开数据库连接
conn = sqlite3.① ('test.db')
print("Opend database successfully")
# 清除已存在的表 students
conn.② ('''DROP TABLE students''')
conn.③
# 创建一个表 students
conn.execute('''④ students
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL);''')
print("Table created successfully")
conn.commit()
# 插入数据
conn.execute("INSERT INTO students(ID,NAME,AGE) VALUES(1,'Allen',25)")
conn.execute("INSERT INTO students(ID,NAME,AGE) VALUES(2,'Maxsu',20)")
conn.execute("INSERT INTO students(ID,NAME,AGE) VALUES(3,'Teddy',24)")
conn.commit()
print("Records Insert successfully")
print("-------------------")
# 读取表 students
⑤ = conn.execute("SELECT * from students")
print("ID NAME AGE")
for it in cursor:
    for i in range(len(it)):
        print(it[i])
    print('\n')
conn.close()
编辑模式