使用Python,熟悉sqlite3的基本操作(查插删改)
一、基本描述
使用Python,熟悉sqlite3的基本操作(查插删改),以及基本数据类型、事务(ACID)。
准备工作:在sqlite3的官网上下载预编译的sqlite文件(windows),包括tools和dll这两个文件。下载后,将它们解压后的文件放到一个文件夹中,并设置sqlite的环境变量。这样就可以直接在命令行打开sqlite3.exe。使用sqlite3.exe是为了方便操作,例如查看表、表头,以及实现交互式的数据库操作。
.open test.db可以创建数据库(open是打开数据库,但若目录下不存在相应文件则会自动创建)。然后输入以下命令新建一张很简单的user表,并插入一条记录。( Enter".help"for instructions。Enterwith";" 数据库描述和操作语言都需要加;作为命令的结束符)
create table user (
id varchar(20) primary key not null,
name varchar(20) not null);
insert into user (id,name) values (1, 'paul');
.databases查看数据库,使用.tables查当前数据库中的表,也可以使用.schema user查看user表的关系模式。可以使用select语句查看数据。
select * from user;
begin;开始一个事务,例如执行插入、删除或更新一条记录,然后执行commit;或rollback;, rollback指令会将上一次事务结束(就是commit或rollback后)的所有数据库操作回滚,恢复至上一次事务结束的状态。
二、简易程序
首先在python中首先创建数据库文件test.db,同样的,若目录下不存在相应文件则会自动创建。
import os
import sqlite3 #导入SQLite驱动:
def create_table(db_name):
#连接到SQlite数据库 'test.db',创建数据库并新建一张表
conn = sqlite3.connect(db_name) #数据库文件是test.db,不存在,则自动创建
print("Database {} created successfully".format(db_name))
cursor = conn.cursor()
# sqlite3中EXECTUEM命令,不区分大小写
cursor.execute('''create table user (
id varchar(20) primary key not null,
name varchar(20) not null);''')
cursor.close()
conn.commit()
conn.close()
print("Table {} created successfully".format('user'))
然后定义CRUD操作
def insert_info(db_name, values):
conn = sqlite3.connect(db_name) #数据库文件是test.db,不存在,则自动创建
cursor = conn.cursor()
#插入一条记录: cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')
cursor.execute("insert into user values (?, ?);", (values[0], values[1]))
print(cursor.rowcount) #通过rowcount获得插入的行数:reusult 1
cursor.close()
conn.commit() #提交事务begin commit rollback end transaction
print("Records created successfully")
conn.close()
def select_info(db_name, id):
conn = sqlite3.connect(db_name) #数据库文件是test.db,不存在,则自动创建
cursor = conn.cursor()
cursor.execute('select * from user where id=?;', (id,))
values = cursor.fetchall() # rows of info
cursor.close()
conn.close()
print(values)
def update_info(db_name, values):
conn = sqlite3.connect(db_name) #数据库文件是test.db,不存在,则自动创建
cursor = conn.cursor()
cursor.execute('update user set name=? where id=?;', (values[1], values[0]))
conn.commit()
cursor.close()
conn.close()
print("updated")
def delete_info(db_name, id):
conn = sqlite3.connect(db_name) #数据库文件是test.db,不存在,则自动创建
cursor = conn.cursor()
cursor.execute('delete from user where id=?;', (id))
conn.commit()
print("Total number of rows deleted :", conn.total_changes)
c = conn.execute('select * from user')
for row in c:
print("id: {}, name: {}".format(row[0], row[1]))
c.close()
cursor.close()
conn.close()
print("delete done successfully")
def show_all(db_name):
conn = sqlite3.connect(db_name)
c = conn.execute('select * from user')
cnt = 1
for row in c:
print("id:{}, name:{}".format(row[0], row[1]), end=" ")
if cnt % 3 == 0:
print("")
cnt += 1
c.close()
conn.close()
:
def main():
db_name = 'test.db'
root_path = os.path.split(os.path.realpath(__file__))[0] + os.sep
file_path = root_path + db_name
print(file_path)
cwd_path = os.getcwd()
print("Current Python Working Directory is " + cwd_path)
os.chdir(root_path) # 将python的工作目录切换到源文件所在目录
print("\nChange Directory to:", root_path)
if not os.path.exists(file_path):
create_table(db_name) # 检查db文件
else:
print("{} file exist already!".format(db_name))
flag = True # 指示位,控制循环
operation = 0 # 操作码, 代表各种操作
op_table = ["Select", "Insert", "Update", "Delete", "ShowAll"]
op_idx = {op:i for i, op in enumerate(op_table)}
idx_op = {i:op for i, op in enumerate(op_table)}
print("\nTest Sqlite3")
while flag != False:
for key, val in op_idx.items():
print("{}:{} ".format(key, val), end=" ")
oper = input("\nPlease input your choice:")
oper = int(oper)
if 4 >= oper >= 0:
print("\nExecute {}".format(idx_op[oper]))
else:
print("Operation code {} error! Please retry!".format(oper))
continue
if oper == 0:
print("Please input id for query") # select
query_id = input()
select_info(db_name, query_id)
elif oper == 1:
print("Please input id and name") # insert
text = input()
values = text.split(" ")
insert_info(db_name, values)
elif oper == 2:
print("Please input id and name") # update
text = input()
values = text.split(" ")
update_info(db_name, values)
elif oper == 3:
print("Please input id for delelte") # delete
del_id = input()
delete_info(db_name, del_id)
elif oper == 4:
show_all(db_name)
sign = input("\nContinue or not,: 0 stop, 1 continue:")
if int(sign) == 0:
flag = False
print("Close Application")
if __name__ == "__main__":
main()