55 lines
1.8 KiB
Python
55 lines
1.8 KiB
Python
# 导入数据库工具
|
|
from db_utils import get_db_connection, close_db_connection
|
|
|
|
# 检查数据库连接是否正常
|
|
def check_database_connection():
|
|
try:
|
|
# 连接数据库
|
|
conn = get_db_connection()
|
|
cursor = conn.cursor()
|
|
|
|
# 执行简单的SQL查询来测试连接
|
|
cursor.execute("SELECT sqlite_version()")
|
|
version = cursor.fetchone()[0]
|
|
|
|
# 检查是否存在必要的表
|
|
necessary_tables = ['users', 'query_records']
|
|
tables_info = []
|
|
|
|
for table in necessary_tables:
|
|
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (table,))
|
|
exists = cursor.fetchone() is not None
|
|
tables_info.append({"name": table, "exists": exists})
|
|
|
|
# 关闭数据库连接
|
|
close_db_connection(conn)
|
|
|
|
# 构造返回结果
|
|
result = {
|
|
"success": True,
|
|
"version": version,
|
|
"tables": tables_info
|
|
}
|
|
|
|
return result
|
|
except Exception as e:
|
|
# 确保在异常情况下也关闭连接
|
|
if 'conn' in locals() and conn:
|
|
close_db_connection(conn)
|
|
|
|
return {
|
|
"success": False,
|
|
"error": str(e)
|
|
}
|
|
|
|
# 如果直接运行此脚本,则执行检查操作
|
|
if __name__ == "__main__":
|
|
result = check_database_connection()
|
|
print(f"数据库连接状态: {'成功' if result['success'] else '失败'}")
|
|
if result['success']:
|
|
print(f"SQLite版本: {result['version']}")
|
|
print("表状态:")
|
|
for table in result['tables']:
|
|
print(f" - {table['name']}: {'存在' if table['exists'] else '不存在'}")
|
|
else:
|
|
print(f"错误信息: {result['error']}") |