64 lines
2.1 KiB
Python
64 lines
2.1 KiB
Python
from utils.sql_utils import SQLUtils
|
||
import datetime
|
||
import os
|
||
import logging
|
||
|
||
def init_database():
|
||
db = SQLUtils('sqlite', database='db/jtDB.db')
|
||
|
||
try:
|
||
db.begin_transaction()
|
||
|
||
# 创建用户表
|
||
create_user_table_sql = """
|
||
CREATE TABLE IF NOT EXISTS user (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
username VARCHAR(50) NOT NULL UNIQUE,
|
||
password VARCHAR(100) NOT NULL,
|
||
create_time TIMESTAMP NOT NULL,
|
||
create_by VARCHAR(50) NOT NULL,
|
||
update_time TIMESTAMP,
|
||
update_by VARCHAR(50),
|
||
is_deleted BOOLEAN DEFAULT FALSE
|
||
);
|
||
"""
|
||
db.execute_query(create_user_table_sql)
|
||
|
||
# 获取当前时间
|
||
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||
|
||
# 插入系统用户
|
||
insert_system_user_sql = """
|
||
INSERT OR IGNORE INTO user (
|
||
username, password, create_time, create_by, is_deleted
|
||
) VALUES (
|
||
'system', '123456', ?, 'system', FALSE
|
||
);
|
||
"""
|
||
db.execute_query(insert_system_user_sql, (current_time,))
|
||
|
||
# 检查是否存在schema.sql文件,如果存在则执行其中的SQL
|
||
schema_file = 'db/schema.sql'
|
||
if os.path.exists(schema_file):
|
||
with open(schema_file, 'r', encoding='utf-8') as f:
|
||
schema_sql = f.read()
|
||
|
||
# 按语句分割并执行SQL
|
||
statements = schema_sql.split(';')
|
||
for statement in statements:
|
||
statement = statement.strip()
|
||
if statement: # 跳过空语句
|
||
db.execute_query(statement)
|
||
|
||
logging.info("已执行schema.sql中的数据库初始化脚本")
|
||
|
||
db.commit_transaction()
|
||
logging.info("数据库初始化成功!")
|
||
except Exception as e:
|
||
db.rollback_transaction()
|
||
logging.error(f"数据库初始化失败: {str(e)}")
|
||
finally:
|
||
db.close()
|
||
|
||
if __name__ == "__main__":
|
||
init_database() |