news 2026/4/26 14:21:13

边走边聊 Python 3.8:Chapter 12+1:MyKB 升级篇-用 SQLite 数据库彻底替换 JSON 存储

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
边走边聊 Python 3.8:Chapter 12+1:MyKB 升级篇-用 SQLite 数据库彻底替换 JSON 存储

MyKB 升级篇:用 SQLite 数据库彻底替换 JSON 存储

MyKB笔记多了以后,JSON 文件读写越来越慢,搜索也卡。
今天我们直接升级,把notes.json彻底换成SQLite 数据库

为什么换 SQLite?

  • Python 3.8内置sqlite3模块(Win7 无需 pip 安装)
  • 查询速度提升 10 倍以上(支持索引)
  • 支持 SQL 语句,以后想加“按标签统计”“按日期范围”超级简单
  • 数据更安全(事务机制,意外断电也不会损坏)
  • 文件体积更小,自动归档更优雅

全部改动只集中在note_manager.py,其他文件几乎不用动!


1、项目结构小调整(只需加一个文件)

MyKB/ ├── main.py ├── config.py ├── note_manager.py ← 重点替换这个 ├── gui.py ├── utils.py ├── notes/ │ ├── mykb.db ← 新增的 SQLite 数据库文件(程序自动创建) │ └── archive/ ← 归档文件夹保持不变 ├── data/ ├── ...

2、完整替换后的 note_manager.py(直接覆盖)

# -*- coding: utf-8 -*-importsqlite3importosfromdatetimeimportdatetime,timedeltaimportjson# 只用于迁移旧数据fromconfigimportNOTES_DIR,ARCHIVE_DIRclassNoteManager:def__init__(self):self.db_path=os.path.join(NOTES_DIR,"mykb.db")self.conn=sqlite3.connect(self.db_path)self.conn.row_factory=sqlite3.Row# 让查询结果可以像字典一样访问self.create_table()self.migrate_from_json()# 首次运行时自动迁移旧 JSON 数据defcreate_table(self):"""创建笔记表 + 索引"""cursor=self.conn.cursor()cursor.execute(''' CREATE TABLE IF NOT EXISTS notes ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, content TEXT NOT NULL, tags TEXT, -- 用逗号分隔存储 date TEXT NOT NULL ) ''')# 为搜索创建索引(速度飞起!)cursor.execute('CREATE INDEX IF NOT EXISTS idx_title ON notes(title)')cursor.execute('CREATE INDEX IF NOT EXISTS idx_content ON notes(content)')cursor.execute('CREATE INDEX IF NOT EXISTS idx_date ON notes(date)')self.conn.commit()defmigrate_from_json(self):"""只运行一次:把旧 notes.json 迁移到 SQLite"""json_path=os.path.join(NOTES_DIR,"notes.json")ifos.path.exists(json_path)andnotself.get_all_notes():print("正在迁移旧 JSON 数据到 SQLite...")withopen(json_path,"r",encoding="utf-8")asf:old_notes=json.load(f)fornoteinold_notes:tags_str=",".join(note.get("tags",[]))self.add_note(note["title"],note["content"],tags_str,note["date"])# 迁移完备份旧文件os.rename(json_path,json_path+".bak")print(f"迁移完成!共{len(old_notes)}条笔记,已备份为 notes.json.bak")defadd_note(self,title,content,tags="",date=None):"""新增笔记"""ifdateisNone:date=datetime.now().strftime("%Y-%m-%d %H:%M:%S")cursor=self.conn.cursor()cursor.execute(''' INSERT INTO notes (title, content, tags, date) VALUES (?, ?, ?, ?) ''',(title,content,tags,date))self.conn.commit()returncursor.lastrowiddefget_all_notes(self):"""获取所有笔记(用于界面列表)"""cursor=self.conn.cursor()cursor.execute("SELECT id, title, date FROM notes ORDER BY date DESC")return[dict(row)forrowincursor.fetchall()]defsearch(self,keyword):"""全文搜索(标题 + 内容 + 标签)"""keyword=f"%{keyword}%"cursor=self.conn.cursor()cursor.execute(''' SELECT id, title, date FROM notes WHERE title LIKE ? OR content LIKE ? OR tags LIKE ? ORDER BY date DESC ''',(keyword,keyword,keyword))return[dict(row)forrowincursor.fetchall()]defget_note_by_id(self,note_id):"""查看单条笔记详情"""cursor=self.conn.cursor()cursor.execute("SELECT * FROM notes WHERE id = ?",(note_id,))row=cursor.fetchone()returndict(row)ifrowelseNonedefauto_archive(self):"""自动归档 >30天的笔记(保持原有逻辑)"""threshold=(datetime.now()-timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S")cursor=self.conn.cursor()cursor.execute("SELECT * FROM notes WHERE date < ?",(threshold,))old_notes=[dict(row)forrowincursor.fetchall()]ifold_notes:fornoteinold_notes:archive_path=os.path.join(ARCHIVE_DIR,f"{note['id']}_{note['title'][:20]}.json")withopen(archive_path,"w",encoding="utf-8")asf:json.dump(note,f,ensure_ascii=False,indent=2)cursor.execute("DELETE FROM notes WHERE id = ?",(note["id"],))self.conn.commit()print(f"已归档{len(old_notes)}条笔记")defclose(self):"""程序退出时关闭连接"""self.conn.close()

3、其他文件只需微调(复制粘贴即可)

1. gui.py 中的小改动(替换对应函数)

# 在 KBApp 类里替换以下两个方法:defrefresh_list(self):foriinself.tree.get_children():self.tree.delete(i)notes=self.manager.get_all_notes()fornoteinnotes:self.tree.insert("","end",values=(note["id"],note["title"],note["date"]))defdo_search(self):kw=self.search_entry.get().strip()ifnotkw:self.refresh_list()returnresults=self.manager.search(kw)foriinself.tree.get_children():self.tree.delete(i)fornoteinresults:self.tree.insert("","end",values=(note["id"],note["title"],note["date"]))defview_note(self):sel=self.tree.selection()
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/26 14:20:04

如何快速配置暗黑3智能宏工具:D3KeyHelper完整实战指南

如何快速配置暗黑3智能宏工具&#xff1a;D3KeyHelper完整实战指南 【免费下载链接】D3keyHelper D3KeyHelper是一个有图形界面&#xff0c;可自定义配置的暗黑3鼠标宏工具。 项目地址: https://gitcode.com/gh_mirrors/d3/D3keyHelper 还在为暗黑3中繁琐的技能操作而烦…

作者头像 李华
网站建设 2026/4/26 14:16:51

Xshell公钥登录背后的原理与安全实践:除了免密,你更该知道这些

Xshell公钥登录背后的原理与安全实践&#xff1a;除了免密&#xff0c;你更该知道这些 每次在终端输入ssh userhost后流畅登录服务器的体验&#xff0c;背后其实隐藏着一场精密的加密对话。公钥认证不仅仅是省去输入密码的便利&#xff0c;更是一套基于非对称加密的安全体系。本…

作者头像 李华
网站建设 2026/4/26 14:16:46

华硕笔记本终极控制方案:G-Helper深度实战指南

华硕笔记本终极控制方案&#xff1a;G-Helper深度实战指南 【免费下载链接】g-helper Lightweight, open-source control tool for ASUS laptops and ROG Ally. Manage performance modes, fans, GPU, battery, and RGB lighting across Zephyrus, Flow, TUF, Strix, Scar, and…

作者头像 李华