Spaces:
Paused

File size: 1,750 Bytes
4a91ea9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import pymysql
import os

# Database configuration
DB_HOST = "49.233.26.60"
DB_PORT = 3306
DB_USER = "root"
DB_PASSWORD = "dianyue"
SQL_FILE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "doc", "数据库schema.sql")

def init_db():
    print(f"Connecting to {DB_HOST}...")
    try:
        connection = pymysql.connect(
            host=DB_HOST,
            port=DB_PORT,
            user=DB_USER,
            password=DB_PASSWORD,
            cursorclass=pymysql.cursors.DictCursor
        )
        
        with connection:
            print("Connected successfully.")
            with connection.cursor() as cursor:
                # Read SQL file
                print(f"Reading SQL file from {SQL_FILE_PATH}...")
                with open(SQL_FILE_PATH, 'r', encoding='utf-8') as f:
                    sql_content = f.read()
                
                # Split commands (this is a simple split, might need more robust parsing if procedures are involved)
                # The schema file uses simple statements ending in ;
                commands = sql_content.split(';')
                
                for command in commands:
                    command = command.strip()
                    if command:
                        print(f"Executing: {command[:50]}...")
                        try:
                            cursor.execute(command)
                        except Exception as e:
                            print(f"Error executing command: {e}")
            
            connection.commit()
            print("Database initialization completed.")
            
    except Exception as e:
        print(f"Failed to connect or execute: {e}")

if __name__ == "__main__":
    init_db()