欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python整合SQLite搭建一個輕量級賬本應(yīng)用

 更新時(shí)間:2025年07月08日 09:13:59   作者:金澤宸  
這篇文章為大家詳細(xì)主要介紹了如何使用Python整合SQLite搭建一個輕量級賬本應(yīng)用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

想記賬,但不想用冗雜 App?這篇帶你用 Python 和 SQLite 快速打造一個能記錄收支、統(tǒng)計(jì)余額、按月查詢的本地賬本工具,輕便、夠用、可擴(kuò)展!

本文目標(biāo)

  • sqlite3 構(gòu)建賬本數(shù)據(jù)庫
  • 支持新增收支、查詢記錄、統(tǒng)計(jì)總額
  • 打造命令行交互式賬本工具
  • 實(shí)現(xiàn)按月過濾和類型篩選

一、數(shù)據(jù)庫設(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ù)庫初始化完成")

運(yùn)行一次:

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("日期(默認(rèn)今天,回車跳過):") 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)計(jì)(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?? 收入總計(jì):¥{total_income:.2f}")
    print(f"?? 支出總計(jì):¥{total_expense:.2f}")
    print(f"?? 當(dāng)前余額:¥{balance:.2f}")

    conn.close()

if __name__ == "__main__":
    list_records()

五、進(jìn)階:按月份或分類過濾查詢(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 實(shí)現(xiàn) ledger.py add/view/filter 多命令工具
  • 導(dǎo)出賬單為 CSV、Excel
  • 添加分類分析圖表(搭配 matplotlib

總結(jié)

SQLite 是個人項(xiàng)目和輕量應(yīng)用最值得掌握的數(shù)據(jù)庫,能存、能查、免服務(wù)、易擴(kuò)展,完美適配一切“小而美”場景。

到此這篇關(guān)于Python整合SQLite搭建一個輕量級賬本應(yīng)用的文章就介紹到這了,更多相關(guān)Python賬本應(yīng)用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論