python3使用sqlite3构建本地持久化缓存

环境:Windows 10_x64

python版本:3.9.2

sqlite3版本:3.34.0

日常python开发中会遇到数据持久化的问题,今天记录下如何使用sqlite3进行数据持久化,并提供示例代码及数据查看工具。

一、背景描述

python应用程序在运行过程中被kill掉(比如版本升级等情况),内存中的运行数据将会丢失,如果能够准实时将数据存储在缓存中,程序下次启动时将继续执行被kill之前的动作。

使用数据库作为持久化是笔记理想的选择,可现实情况可能需要python脚本进行本地持久化,相较于pickle等方式,sqlite3的持久化方式可扩展性比较强,方便后续迁移到mysql等数据库。

二、具体实现

1、基础使用示例

  • 查看版本信息
复制代码
import sqlite3
print(sqlite3.version_info) #显示sqlite3版本信息
print(sqlite3.sqlite_version) #显示SQLite版本信息
  • 数据库创建或连接
复制代码
conn = sqlite3.connect("test1.db")
cur = conn.cursor()
  • 数据表创建
复制代码
dbCreate = '''
CREATE TABLE user(
    user_id int,
    user_name text,
    password text
)
'''
cur.executescript(dbCreate)
conn.commit()
  • 插入数据
复制代码
conn.execute("INSERT INTO user (user_id,user_name,password) VALUES(1,'user1','123456')")
conn.commit()
  • 查询数据
复制代码
cursor = conn.execute("SELECT * FROM user")
for row in cursor.fetchall():
    print(row)

完整示例代码如下:

复制代码
#! /usr/bin/env python3
#--*-- ebcoding:utf-8 --*--

import sqlite3

dbCreate = '''
CREATE TABLE user(
    user_id int,
    user_name text,
    password text
)
'''

# 创建或连接数据库
conn = sqlite3.connect("test1.db")
cur = conn.cursor()

cur.executescript(dbCreate)
conn.commit()

conn.execute("INSERT INTO user (user_id,user_name,password) VALUES(1,'user1','123456')")
conn.execute("INSERT INTO user (user_id,user_name,password) VALUES(2,'user2','123457')")
conn.commit()

cursor = conn.execute("SELECT * FROM user")
for row in cursor.fetchall():
    print(row)

conn.close()
相关推荐
HitpointNetSuite18 小时前
连锁餐饮行业ERP系统如何选择?
大数据·数据库·oracle·netsuite·erp
百***170718 小时前
MySQL 常用 SQL 语句大全
数据库·sql·mysql
百***659518 小时前
mysql如何发现慢查询sql
数据库·sql·mysql
资深web全栈开发18 小时前
PostgreSQL 实战指南(面向 MySQL 开发者)
数据库·mysql·postgresql
TG:@yunlaoda360 云老大18 小时前
谷歌云数据库服务概览:关系型与 NoSQL 的多元选择与应用场景解析
数据库·nosql·googlecloud
hello_fracong18 小时前
PostgreSQL (零-1) Windows安装PostgreSQL
数据库·windows·postgresql
清空mega18 小时前
第五章《Android 数据存储》
数据库·android studio
q***333719 小时前
Redis简介、常用命令及优化
数据库·redis·缓存
武子康19 小时前
Java-168 Neo4j CQL 实战:WHERE、DELETE/DETACH、SET、排序与分页
java·开发语言·数据库·python·sql·nosql·neo4j