无限星辰工作室-客户无限互联网动力之源

标题: sqlite数据库转换到mysql操作流程 [打印本页]

作者: crx349    时间: 16 小时前
标题: sqlite数据库转换到mysql操作流程
需求:需要将sqlite数据库导入mysql
运行环境:Centos 7 x64  Python2.7
解决步骤:
1.先将sqlite数据库导出为mysql
  1. sqlite3 xmspace.net.db .dump > xmspace.net.sql
复制代码


2.用python进行转换

  1. #-- coding:UTF-8 --
  2. import re
  3. import io


  4. def convert_sqlite_to_mysql(sql):
  5.     # 移除 PRAGMA 语句
  6.     sql = re.sub(r'PRAGMA .*?;', '', sql)

  7.     # 修改 BEGIN TRANSACTION 为 START TRANSACTION
  8.     sql = sql.replace('BEGIN TRANSACTION;', 'START TRANSACTION;')

  9.     # 替换 COMMIT TRANSACTION 为 COMMIT
  10.     sql = sql.replace('COMMIT;', 'COMMIT;')

  11.     # 替换 ROLLBACK TRANSACTION 为 ROLLBACK
  12.     sql = sql.replace('ROLLBACK;', 'ROLLBACK;')

  13.     # 修改 AUTOINCREMENT 为 AUTO_INCREMENT
  14.     sql = sql.replace('AUTOINCREMENT', 'AUTO_INCREMENT')

  15.     # 替换数据类型
  16.     sql = sql.replace('INTEGER', 'INT')
  17.     sql = sql.replace('TEXT', 'VARCHAR(255)')

  18.     # 替换双引号为反引号
  19.     sql = sql.replace('"', '`')

  20.     # 添加 CHARACTER SET utf8mb4 到表定义中
  21.     sql = re.sub(r'CREATE TABLE `(.*?)` \(', r'CREATE TABLE IF NOT EXISTS `\1` (', sql)
  22.     # sql = re.sub(r'\);', r') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;', sql)

  23.     # 处理 INSERT 语句,确保数据字符集正确
  24.     sql = re.sub(r'INSERT INTO `(.*?)` \((.*?)\) VALUES', r'INSERT INTO `\1` (\2) VALUES', sql)
  25.     sql = re.sub(r'INSERT INTO `sqlite_sequence`.*?;', '', sql)
  26.     return sql

  27. # 读取原始的 SQLite dump 文件
  28. with io.open('xmspace.net.sql', 'r', encoding='utf-8') as file:
  29.     sql_dump = file.read()

  30. # 转换为 MySQL 兼容的 SQL
  31. mysql_compatible_sql = convert_sqlite_to_mysql(sql_dump)

  32. # 将转换后的 SQL 写入新的文件
  33. with io.open('xmspace.net_mysql.sql', 'w', encoding='utf-8') as file:
  34.     file.write(mysql_compatible_sql)

  35. print("SQL conversion complete. Please check 'dump_mysql.sql' for MySQL import.")
复制代码







欢迎光临 无限星辰工作室-客户无限互联网动力之源 (https://www.xmspace.net/) Powered by Discuz! X3.4