基于Python+Sqlite3实现最简单的CRUD
一、基本描述
使用Python,熟悉sqlite3的基本操作(查插删改),以及基本数据类型、事务(ACID)。
准备工作:在sqlite3的官网上下载预编译的sqlite文件(windows),包括tools和dll这两个文件。下载后,将它们解压后的文件放到一个文件夹中,并设置sqlite的环境变量。这样就可以直接在命令行打开sqlite3.exe。使用sqlite3.exe是为了方便操作,例如查看表、表头,以及实现交互式的数据库操作。
先使用命令行熟悉,sqlite3。第一步打开cmd,输入sqlite3进入sqlite的命令行模式,输入.open test.db可以创建数据库(open是打开数据库,但若目录下不存在相应文件则会自动创建)。然后输入以下命令新建一张很简单的user表,并插入一条记录。( Enter ".help" for instructions。Enter SQL statements terminated with a ";" 数据库描述和操作语言都需要加;作为命令的结束符)
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()
基于Python+Sqlite3实现最简单的CRUD的更多相关文章
- 基于Python使用SVM识别简单的字符验证码的完整代码开源分享
关键字:Python,SVM,字符验证码,机器学习,验证码识别 1 概述 基于Python使用SVM识别简单的验证字符串的完整代码开源分享. 因为目前有了更厉害的新技术来解决这类问题了,但是本文作 ...
- Python 基于Python及zookeeper实现简单分布式任务调度系统设计思路及核心代码实现
基于Python及zookeeper实现简单分布式任务调度系统设计思路及核心代码实现 by:授客 QQ:1033553122 测试环境 功能需求 实现思路 代码实践(关键技术点实现) 代码模块组织 ...
- 如何简单实现接口自动化测试(基于 python) 原博主地址https://blog.csdn.net/gitchat/article/details/77849725
如何简单实现接口自动化测试(基于 python) 2017年09月05日 11:52:25 阅读数:9904 GitChat 作者:饿了么技术社区 原文:如何简单实现接口自动化测试(基于 python ...
- 一次简单完整的自动化登录测试-基于python+selenium进行cnblog的自动化登录测试
Web登录测试是很常见的测试,手动测试大家再熟悉不过了,那如何进行自动化登录测试呢!本文就基于python+selenium结合unittest单元测试框架来进行一次简单但比较完整的cnblog自动化 ...
- Websocket - Websocket原理(握手、解密、加密)、基于Python实现简单示例
一.Websocket原理(握手.解密.加密) WebSocket协议是基于TCP的一种新的协议.WebSocket最初在HTML5规范中被引用为TCP连接,作为基于TCP的套接字API的占位符.它实 ...
- 简单实现接口自动化测试(基于python+unittest)
简单实现接口自动化测试(基于python+unittest) 简介 本文通过从Postman获取基本的接口测试Code简单的接口测试入手,一步步调整优化接口调用,以及增加基本的结果判断,讲解Pytho ...
- 实用的Python(3)超简单!基于Python搭建个人“云盘”
1 简介 当我们想要从本地向云服务器上传文件时,比较常用的有pscp等工具,但避免不了每次上传都要写若干重复的代码,而笔者最近发现的一个基于Python的工具updog,可以帮助我们在服务器上搭建类似 ...
- python sqlite3简单操作
python sqlite3简单操作(原创)import sqlite3class CsqliteTable: def __init__(self): pass def linkSqlite3(sel ...
- 超简单!基于Python搭建个人“云盘”
1. 简介 当我们想要从本地向云服务器上传文件时,比较常用的有pscp等工具,但避免不了每次上传都要写若干重复的代码,而笔者最近发现的一个基于Python的工具updog,可以帮助我们在服务器上搭建类 ...
随机推荐
- Red Hat牵头推进NVFS文件系统
开源Linux 长按二维码加关注~ 上一篇:Linux中几个正则表达式的用法 由 Red Hat 工程师牵头的团队,正在为 Linux/开源社区研究名为 NVFS 的文件系统.NVFS 的目标是成为像 ...
- 不再空谈AI,从打造一台智能无人机开始
对于大多数无人机爱好者来说,能自己从头开始组装一台无人机,之后加入AI算法,能够航拍,可以目标跟踪,是心中的梦想. 并且,亲自从零开始完成复杂系统,这是掌握核心技术的必经之路. 开课吧特邀北京航空航天 ...
- ngx-lua实现高级限流方式一
基于POST请求体中的某个参数限流 背景 电商平台有活动,活动涉及优惠券的抢券,优惠券系统对大并发支持略差,为了保护整体系统平稳,因此在入口Nginx层对抢券接口做了一层限流. 完整实现如下: lua ...
- deepin安装jdk配置环境
下载一个jdk压缩包https://download.oracle.com/java/18/latest/jdk-18_linux-x64_bin.tar.gz 这个包,不用安装,下下来,直接解压,然 ...
- ElasticSearch7.3学习(二十三)----RestHighLevelClient Java api实现match_all、ids、match、term、multi_match、bool、filter、sort等不同的搜索方式
1.数据准备 首先创建book索引 PUT /book/ { "settings": { "number_of_shards": 1, "number ...
- 生成器对象(自定义迭代器),自定义range方法,模块
自定义迭代器 一 .生成器与yield ''' 我们得到一个迭代器通常都是调用可迭代对象的__iter__方法 ,例如 list.iter() 得到一个迭代器, 但是当list很大时候,就违背了pyt ...
- Maven生成可以直接执行的jar包
要想jar包能直接通过java -jar xxx.jar运行,需要满足: 1.在jar包中的META-INF/MANIFEST.MF中指定Main-Class,这样才能确定程序的入口在哪里: 2.要能 ...
- CXP 协议中upconnection 与downconnection的说明及其区别
概述 CXP定义了一个DEVICE和HOST之间点对点的连接协议.CXP的一个连接包含了一个MASTER物理连接和若干可选的SLAVE连接,每一个连接都定义了一组逻辑通道用于传输图像数据.实时触发.设 ...
- React简单教程-1-组件
前言 React,Facebook开发的前端框架.当时Facebook对市面上的前端框架都不满意,于是自己捣鼓出了React,使用后觉得特别好用,于是就在2013年开源了. 我也用React开发了一个 ...
- JAVA - 启动线程有哪几种方式
JAVA - 启动线程有哪几种方式 一.继承Thread类创建线程类 (1)定义Thread类的子类,并重写该类的run方法,该run方法的方法体就代表了线程要完成的任务.因此把run()方法称为执行 ...