def index2(request):
# 如果数据库存在,直接连接;否则会创建相应的数据库
connect = sqlite3.connect('TEST.db')
# 创建一个游标,用于数据库操作:
cursor = connect.cursor()
# 创建表
cursor.execute('create table if not exists T_BASE (ID INT PRIMARY KEY, NAME VARCHAR(20) NOT NULL)')
# 插入数据
# 第二种:execute multiple commands
students = [(2, 'mark'),(3, 'tom'),(4, 'lucy'),(5, 'jimi')]
cursor.executemany('insert into T_BASE values (?,?)', students)
# 第三种:using the placeholder
# cursor.execute("insert into T_BASE values (?,?)", (7, 'kim'))
# 查询数据
# 第一种:retrieve one record
cursor.execute('SELECT * FROM T_BASE order by ID desc')
print(cursor.fetchone()) # 第1条记录
print(cursor.fetchone()) # 第2条记录
# 第二种:retrieve all records as a list
cursor.execute('select * from T_BASE order by ID desc')
values = cursor.fetchall()
print(values)
# 第三种:terate through the records
rs = cursor.execute('select * from T_BASE order by ID desc')
for row in rs:
print(row)
# 更新数据
# cursor.execute('UPDATE T_BASE SET NAME= 'MARY' WHERE ID = 1')
# 删除数据
# cursor.execute('DELETE FROM T_BASE WHERE ID = 1')
# 结束
# 关闭游标
cursor.close()
# 提交事务
connect.commit()
# 关闭数据库连接
connect.close()
return HttpResponse(values)
网友评论