1. 选择编程语言和数据库
- 编程语言:Python(易于学习,适合初学者)
- 数据库:SQLite(轻量级,内嵌在Python标准库中,无需额外安装)
2. 设计数据库
你需要一个数据库来存储记账信息,例如:
- 表名:
transacti*
- 列:
id
(自增主键)、date
(日期)、description
(描述)、amount
(金额)、type
(收入/支出)
3. 编写Python脚本
3.1 导入必要的库
import sqlite3 from datetime import datetime
3.2 创建或连接数据库
def create_connection(db_file): """ 创建一个数据库连接 """ conn = None try: conn = sqlite3.connect(db_file) return conn except sqlite3.Error as e: print(e) return conn def create_table(conn): """ 创建一个表 """ try: sql_create_transacti*_table = """CREATE TABLE IF NOT EXISTS transacti* ( id integer PRIMARY KEY, date text, description text, amount real, type text );""" cursor = conn.cursor() cursor.execute(sql_create_transacti*_table) except sqlite3.Error as e: print(e)
3.3 添加记账条目
def add_transaction(conn, date, description, amount, type): """ 添加一条交易记录 """ sql = ''' INSERT INTO transacti*(date,description,amount,type) VALUES(?,?,?,?) ''' cur = conn.cursor() cur.execute(sql, (date, description, amount, type)) conn.commit() return cur.lastrowid
3.4 查询记账条目def query_transacti*(conn): """ 查询所有交易记录 """ cur = conn.cursor() cur.execute("SELECT * FROM transacti*") rows = cur.fe*hall() return rows
3.5 主程序
def query_transacti*(conn): """ 查询所有交易记录 """ cur = conn.cursor() cur.execute("SELECT * FROM transacti*") rows = cur.fe*hall() return rows
4. 运行脚本
将上述代码保存为一个Python文件(例如
accounting.py
),然后在命令行中运行它:python accounting.py