30 lines
732 B
Python
30 lines
732 B
Python
|
|
import sqlite3
|
||
|
|
from pathlib import Path
|
||
|
|
import os
|
||
|
|
from dotenv import load_dotenv
|
||
|
|
|
||
|
|
load_dotenv()
|
||
|
|
|
||
|
|
DB_FILE = os.getenv("DB_FILE")
|
||
|
|
SQL_FILE = os.getenv("SQL_FILE")
|
||
|
|
|
||
|
|
# 初始化数据库
|
||
|
|
def init_db():
|
||
|
|
conn = sqlite3.connect(DB_FILE, timeout=30, check_same_thread=False)
|
||
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
||
|
|
cur = conn.cursor()
|
||
|
|
sql = Path(SQL_FILE).read_text("utf-8")
|
||
|
|
cur.executescript(sql)
|
||
|
|
conn.commit()
|
||
|
|
conn.close()
|
||
|
|
print(f"数据库 {DB_FILE} 创建完成")
|
||
|
|
|
||
|
|
# 获取连接
|
||
|
|
def get_conn():
|
||
|
|
conn = sqlite3.connect(DB_FILE, timeout=30, check_same_thread=False)
|
||
|
|
conn.row_factory = sqlite3.Row
|
||
|
|
conn.execute("PRAGMA foreign_keys=ON")
|
||
|
|
return conn
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
init_db()
|