导入MySQL表DUMP文件时,VALUES含特殊字符导致导入失败如何解决?
解决SQL Dump文件导入时因HTML转义符号错误分割语句的问题
问题场景
你有一个MySQL表的dump文件,核心内容如下:
CREATE TABLE `smf_messages` ( `id_msg` int UNSIGNED NOT NULL, -- 其他字段省略 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; -- -- Dumping data for table `smf_messages` -- INSERT INTO `smf_messages` (`id_msg`, -- 其他字段省略 ) VALUES (1, 1, 5, 1673905780, 0, 1, 'Welcome to "SMF!"', -- 其他值省略 , 1, 0);
使用以下代码导入时失败:
with open(dump_file, encoding='utf-8-sig') as f: lines = f.read() commands = lines.replace(' ', ' ').split(';')
失败原因:手动用;分割SQL语句时,会误将HTML转义后的特殊字符(比如 里的;)当成SQL语句的结束符,导致语句被错误拆分,最终导入失败。
解决方案
方案1:使用MySQL官方工具导入(推荐)
直接用mysql命令行工具导入dump文件,工具会自动处理SQL语句中的各种转义和特殊字符,是最可靠的方式:
mysql -u username -p database_name < dump_file.sql
输入密码后即可完成导入,无需手动处理文本内容。
方案2:用专业SQL解析库处理(Python环境)
不要自己手动分割SQL,使用sqlparse库来正确解析SQL语句,它能识别字符串内的特殊字符,不会误拆分:
- 先安装库:
pip install sqlparse
- 改写导入代码:
import sqlparse import html with open(dump_file, encoding='utf-8-sig') as f: sql_content = f.read() # 先还原HTML转义字符,比如把&nbsp;转成空格 sql_content = html.unescape(sql_content) # 解析SQL语句,自动忽略字符串内的分号 statements = sqlparse.split(sql_content) # 遍历执行每个合法的SQL语句 for stmt in statements: stmt = stmt.strip() if stmt: # 替换成你的数据库执行逻辑,比如cursor.execute(stmt) print(f"执行语句:{stmt[:100]}...")
方案3:手动处理时避开字符串内的分号
如果一定要手动处理,可以通过状态标记法识别字符串区域,只在字符串外的;处分割:
import html with open(dump_file, encoding='utf-8-sig') as f: sql_content = f.read() # 先还原HTML转义字符 sql_content = html.unescape(sql_content) commands = [] current_stmt = [] in_single_quote = False in_double_quote = False for char in sql_content: # 切换单引号状态 if char == "'" and not in_double_quote: in_single_quote = not in_single_quote # 切换双引号状态 elif char == '"' and not in_single_quote: in_double_quote = not in_double_quote # 仅在非字符串区域处理分号分割 elif char == ';' and not in_single_quote and not in_double_quote: current_stmt.append(char) commands.append(''.join(current_stmt).strip()) current_stmt = [] else: current_stmt.append(char) # 处理最后一段无分号的语句 if current_stmt: commands.append(''.join(current_stmt).strip()) # 遍历执行分割后的语句 for cmd in commands: if cmd: # 替换成你的数据库执行逻辑 pass
内容的提问来源于stack exchange,提问作者Rec
相关产品推荐
相关产品推荐

