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
| import re import os
# 定义一个函数来转换 SQL Server 语法为 MySQL 兼容语法 def convert_sql(sql_server_command): # 替换 INSERT -> INSERT INTO sql_server_command = re.sub(r'\bINSERT\b', 'INSERT INTO', sql_server_command) # 替换 [dbo].[Big_1_shunfeng] -> Big_1_shunfeng sql_server_command = re.sub(r'\[dbo\]\.\[([^\]]+)\]', r'\1', sql_server_command) # 替换字段名:例如:[name] -> name sql_server_command = re.sub(r'\[([^\]]+)\]', r'\1', sql_server_command) # 替换 N'' -> ''(去除 N 字符) sql_server_command = re.sub(r"N''", "''", sql_server_command) # 替换 N'xxx' -> 'xxx'(去除 N 前缀,适应 MySQL) sql_server_command = re.sub(r"N'([^']+)'", r"'\1'", sql_server_command) # 为每行末尾加上分号(排除已经带有分号的行) sql_server_command = re.sub(r'(?<!;)\s*$', ';', sql_server_command, flags=re.MULTILINE) return sql_server_command
# 定义一个函数来处理整个 SQL 文件 def process_sql_file(input_file_path): # 获取源文件名(不包含扩展名) file_name, file_extension = os.path.splitext(os.path.basename(input_file_path)) # 新文件名 output_file_path = f"{file_name}_mysql{file_extension}"
with open(input_file_path, 'r', encoding='utf-8') as input_file, \ open(output_file_path, 'w', encoding='utf-8') as output_file: # 逐行读取文件 for line in input_file: # 去掉行两端的空白字符 line = line.strip()
# 仅处理以 INSERT 开头的行 if line.startswith('INSERT'): # 转换 SQL 语法 converted_line = convert_sql(line) # 写入新文件并加上换行符 output_file.write(converted_line + '\n') print(f"转换完成,新文件已保存为: {output_file_path}")
# 调用函数,处理文件 input_file_path = 'shunfeng_converted.sql' # 替换为你的源文件路径 process_sql_file(input_file_path)
|