49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
可选片段:最小 SQLite 示例(请复制后按需修改)
|
||
==============================================
|
||
|
||
【用途】
|
||
演示「单表 + 自增主键 + INTEGER 时间戳」的一种严谨写法;与具体业务无关。
|
||
|
||
【使用步骤】
|
||
1. 复制到 scripts/db_example.py(或并入你的模块)。
|
||
2. 修改 TABLE_SQL 中的表名与字段;保持时间字段为 INTEGER Unix 秒(UTC)若需跨时区一致。
|
||
3. 在入口脚本中仅在需要持久化时 import。
|
||
|
||
【注意】
|
||
- 不在模板中做迁移兼容;schema 变更请用你们组织的迁移策略。
|
||
- 数据库文件路径建议:get_skill_data_dir() / "skill.db"(paths_snippet 中函数)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import sqlite3
|
||
import time
|
||
|
||
# 示例表:与任何业务无关
|
||
TABLE_SQL = """
|
||
CREATE TABLE IF NOT EXISTS template_audit (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT, -- 自增主键
|
||
action TEXT NOT NULL, -- 动作标识,如 health_ok
|
||
created_at INTEGER NOT NULL -- Unix 秒 UTC
|
||
);
|
||
"""
|
||
|
||
|
||
def connect(db_path: str) -> sqlite3.Connection:
|
||
return sqlite3.connect(db_path)
|
||
|
||
|
||
def init_db(conn: sqlite3.Connection) -> None:
|
||
conn.execute(TABLE_SQL)
|
||
conn.commit()
|
||
|
||
|
||
def record_action(conn: sqlite3.Connection, action: str) -> None:
|
||
conn.execute(
|
||
"INSERT INTO template_audit (action, created_at) VALUES (?, ?)",
|
||
(action, int(time.time())),
|
||
)
|
||
conn.commit()
|