## 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() ```