Python整合SQLite搭建一個輕量級賬本應用
想記賬,但不想用冗雜 App?這篇帶你用 Python 和 SQLite 快速打造一個能記錄收支、統(tǒng)計余額、按月查詢的本地賬本工具,輕便、夠用、可擴展!
本文目標
- 用
sqlite3構建賬本數(shù)據(jù)庫 - 支持新增收支、查詢記錄、統(tǒng)計總額
- 打造命令行交互式賬本工具
- 實現(xiàn)按月過濾和類型篩選
一、數(shù)據(jù)庫設計
創(chuàng)建一張records表
CREATE TABLE records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL, -- 收入 / 支出
category TEXT NOT NULL, -- 分類(工資、餐飲、交通等)
amount REAL NOT NULL, -- 金額
note TEXT, -- 備注
date TEXT NOT NULL -- 日期(YYYY-MM-DD)
)
二、初始化數(shù)據(jù)庫(init_db.py)
import sqlite3
conn = sqlite3.connect("ledger.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL,
category TEXT NOT NULL,
amount REAL NOT NULL,
note TEXT,
date TEXT NOT NULL
)
""")
conn.commit()
conn.close()
print("? 數(shù)據(jù)庫初始化完成")
運行一次:
python init_db.py


三、添加收支記錄(add.py)
import sqlite3
from datetime import datetime
def add_record():
rtype = input("類型(收入/支出):")
category = input("分類(工資/餐飲等):")
amount = float(input("金額:"))
note = input("備注(可選):")
date = input("日期(默認今天,回車跳過):") or datetime.now().strftime("%Y-%m-%d")
conn = sqlite3.connect("ledger.db")
cursor = conn.cursor()
cursor.execute("""
INSERT INTO records (type, category, amount, note, date)
VALUES (?, ?, ?, ?, ?)
""", (rtype, category, amount, note, date))
conn.commit()
conn.close()
print("? 記錄添加成功")
if __name__ == "__main__":
add_record()
四、查詢總覽 & 統(tǒng)計(view.py)
import sqlite3
def list_records():
conn = sqlite3.connect("ledger.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM records ORDER BY date DESC")
rows = cursor.fetchall()
total_income = 0
total_expense = 0
for row in rows:
id, rtype, cat, amt, note, date = row
print(f"{id}. [{rtype}] {cat} ¥{amt} - {note} ({date})")
if rtype == "收入":
total_income += amt
else:
total_expense += amt
balance = total_income - total_expense
print(f"\n?? 收入總計:¥{total_income:.2f}")
print(f"?? 支出總計:¥{total_expense:.2f}")
print(f"?? 當前余額:¥{balance:.2f}")
conn.close()
if __name__ == "__main__":
list_records()
五、進階:按月份或分類過濾查詢(filter.py)
import sqlite3
def filter_by_month(month): # 格式:2025-07
conn = sqlite3.connect("ledger.db")
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM records WHERE date LIKE ?
ORDER BY date DESC
""", (f"{month}%",))
for row in cursor.fetchall():
print(row)
conn.close()
filter_by_month("2025-07")
使用演示
python add.py # 添加記錄 python view.py # 查看總覽 python filter.py # 按月過濾


拓展挑戰(zhàn)
- 使用
argparse實現(xiàn)ledger.py add/view/filter多命令工具 - 導出賬單為 CSV、Excel
- 添加分類分析圖表(搭配
matplotlib)
總結
SQLite 是個人項目和輕量應用最值得掌握的數(shù)據(jù)庫,能存、能查、免服務、易擴展,完美適配一切“小而美”場景。
到此這篇關于Python整合SQLite搭建一個輕量級賬本應用的文章就介紹到這了,更多相關Python賬本應用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
pandas 中對特征進行硬編碼和onehot編碼的實現(xiàn)
今天小編就為大家分享一篇pandas 中對特征進行硬編碼和onehot編碼的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python使用PyFiglet實現(xiàn)終端輸出炫酷的ASCII藝術字效果
PyFiglet是一個基于Python的純文本到ASCII藝術字轉換工具,它實現(xiàn)了FIGlet的完整功能,本文給大家介紹了Python如何使用PyFiglet實現(xiàn)終端輸出炫酷的ASCII藝術字效果,需要的朋友可以參考下2025-12-12
Linux上使用Python統(tǒng)計每天的鍵盤輸入次數(shù)
這篇文章主要介紹了Linux上使用Python統(tǒng)計每天的鍵盤輸入次數(shù),非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04
Python 中數(shù)組和數(shù)字相乘時的注意事項說明
這篇文章主要介紹了Python 中數(shù)組和數(shù)字相乘時的注意事項說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05
一個基于flask的web應用誕生 flask和mysql相連(4)
一個基于flask的web應用誕生第四篇,這篇文章主要介紹了如何讓flask和mysql進行互聯(lián),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
Python使用Selenium實現(xiàn)Web自動化的完整指南
Selenium?是一個強大的開源?Web?自動化工具集,本文將作為一份面向完全新手的系統(tǒng)性指南,帶你一步步了解什么是?Selenium,以及如何使用?Python?編寫你的第一個?Web?自動化腳本2026-03-03

