File size: 2,710 Bytes
49fabfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
## Convert mysql sang sqlite

Giả sử tôi đặt tên file .sql sử dụng trong mysql là schema.sql

```python

import sqlite3
import re
import os

# Cấu hình tên file
INPUT_SQL_FILE = 'schema.sql'  # Tên file SQL gốc của bạn
OUTPUT_DB_FILE = 'database.db'     # Tên file SQLite muốn tạo

def convert_mysql_to_sqlite(sql_content):
    # 1. Xóa các dòng comment SQL (bắt đầu bằng -- hoặc /*)
    sql_content = re.sub(r'/\*.*?\*/', '', sql_content, flags=re.DOTALL)
    
    # 2. Xóa cú pháp COMMENT '...' của MySQL
    # Regex này tìm từ khóa COMMENT theo sau là chuỗi trong dấu nháy đơn
    sql_content = re.sub(r"COMMENT\s+'.*?'", "", sql_content)
    
    # 3. Xử lý AUTO_INCREMENT
    # SQLite tự động tăng nếu là INTEGER PRIMARY KEY, nên chỉ cần xóa từ khóa này
    sql_content = re.sub(r"AUTO_INCREMENT", "", sql_content, flags=re.IGNORECASE)
    
    # 4. Thay thế kiểu dữ liệu BIT(1) thành INTEGER (SQLite không có BIT)
    sql_content = re.sub(r"BIT$1$", "INTEGER", sql_content, flags=re.IGNORECASE)
    
    # 5. Thay thế giá trị bit b'0', b'1' thành 0, 1
    sql_content = re.sub(r"b'0'", "0", sql_content)
    sql_content = re.sub(r"b'1'", "1", sql_content)
    
    # 6. Xóa các thiết lập cuối bảng của MySQL (ENGINE=InnoDB...)
    sql_content = re.sub(r"\) ENGINE=.*?;", ");", sql_content, flags=re.DOTALL)
    
    # 7. Thay thế \' trong chuỗi thành '' (cách escape của SQLite)
    sql_content = sql_content.replace("\\'", "''")
    
    return sql_content

# Xóa file cũ nếu có
if os.path.exists(OUTPUT_DB_FILE):
    os.remove(OUTPUT_DB_FILE)
    
# Kết nối SQLite
conn = sqlite3.connect(OUTPUT_DB_FILE)
cursor = conn.cursor()

print("Đang đọc và xử lý file SQL...")

try:
    with open(INPUT_SQL_FILE, 'r', encoding='utf-8') as f:
        raw_sql = f.read()
        
    clean_sql = convert_mysql_to_sqlite(raw_sql)
    
    # Tách các câu lệnh bằng dấu chấm phẩy và thực thi từng câu
    statements = clean_sql.split(';')
    
    count = 0
    for statement in statements:
        if statement.strip():
            try:
                cursor.execute(statement)
                count += 1
            except sqlite3.Error as e:
                print(f"Lỗi tại câu lệnh: {statement[:50]}...")
                print(f"Chi tiết: {e}")

    conn.commit()
    print(f"Xong! Đã tạo file '{OUTPUT_DB_FILE}' với {count} câu lệnh thành công.")

except FileNotFoundError:
    print(f"Lỗi: Không tìm thấy file '{INPUT_SQL_FILE}'")
except Exception as e:
    print(f"Lỗi không mong muốn: {e}")
finally:
    conn.close()
```