python+SQLite3数据库的基本操作
创建数据库
def data_save(data):
import sqlite3
conn = sqlite3.connect('database1.db') # 创建连接一个名为database1的数据库文件
c = conn.cursor() # 获取游标
print('数据库连接成功')
conn.commit() # 提交数据库操作
conn.close() # 关闭连接
增加数据
sql = '''insert into target_infomation
(threat_degree,type,v,distance)
values
(:T,:I ,:V,:D)
'''
evi_list = ['I', 'V', 'D']
for row in data:
print(row)
c.execute(sql, row) # 执行 sql 语句
print('数据插入成功')
删除数据
# 删除全部数据
sql = '''delete from target_infomation'''
c.execute(sql)
print('删除所有成功')
# 条件删除数据
sql = '''delete from target_infomation where (threat_degree = :T)'''
c.execute(sql, {'T': 1})
print('删除成功')
修改数据
# 修改数据
sql = '''update target_infomation set name=:s_name,age=:s_age where (type=:I) '''
c.execute(sql, {'T': 1, 'I': 1, 'V': 0,'D': 2})
print('修改成功')
查询数据
# 查询全部
sql = '''SELECT threat_degree,type,v,distance from target_infomation'''
for row in c.execute(sql):
print(row)
print('查询成功')
# 条件查询
sql = '''SELECT threat_degree,type,v,distance from target_infomation where (type=:I)'''
stu = c.execute(sql, {'I': 1})
print('查询成功')