55 lines
1.6 KiB
Python
55 lines
1.6 KiB
Python
import mysql.connector
|
|
from mysql.connector import Error
|
|
import configparser
|
|
import hashlib
|
|
|
|
# 读取配置文件
|
|
config = configparser.ConfigParser()
|
|
config.read('backend/config.conf')
|
|
|
|
|
|
def get_connection():
|
|
try:
|
|
connection = mysql.connector.connect(
|
|
host=config['mysql']['host'],
|
|
port=config['mysql']['port'],
|
|
user=config['mysql']['user'],
|
|
password=config['mysql']['password'],
|
|
database=config['mysql']['database'],
|
|
init_command="SET time_zone='+08:00'"
|
|
)
|
|
return connection
|
|
except Error as e:
|
|
print(f"Error connecting to MySQL: {e}")
|
|
return None
|
|
|
|
|
|
def initialize_database():
|
|
"""
|
|
初始化数据库
|
|
"""
|
|
connection = get_connection()
|
|
if not connection:
|
|
raise Exception("Database connection failed!")
|
|
|
|
try:
|
|
cursor = connection.cursor(dictionary=True)
|
|
cursor.execute("SELECT COUNT(*) AS user_count FROM users;")
|
|
result = cursor.fetchone()
|
|
|
|
if result['user_count'] == 0:
|
|
admin_password = hashlib.md5("admin".encode()).hexdigest()
|
|
cursor.execute(
|
|
"INSERT INTO users (username, password, user_type) VALUES (%s, %s, %s);",
|
|
('admin', admin_password, 'admin')
|
|
)
|
|
connection.commit()
|
|
print("Default admin user created: username=admin, password=admin")
|
|
else:
|
|
print("Users table already initialized.")
|
|
except Error as e:
|
|
print(f"Error during database initialization: {e}")
|
|
finally:
|
|
cursor.close()
|
|
connection.close()
|