Python如何从包含多SQL语句的字符串中提取指定表的INSERT语句
SQL提取指定表INSERT语句解决方案
推荐优先使用专业SQL解析库实现,该方案不会被字段值内的特殊字符干扰,稳定性远高于正则,完全适配数千条插入值、数十张表的业务场景。
方案1:使用sqlparse解析(生产环境首选)
步骤
- 安装依赖:
pip install sqlparse - 实现代码:
import sqlparse sql = """DROP TABLE IF EXISTS table1; ALTER TABLE table1 DROP PRIMARY KEY; INSERT INTO table1 (id, created, name, telefonnummer, erPatient_id) VALUES (1, '2015-08-06 12;09:08', ' ', ' ', 16528), (2, '2015-08-06 12:43:11', ' ', ' ', 16529) ; INSERT INTO table2 (comment, id) VALUES ('hello this is a semicolon ;', 2);""" # 解析SQL拆分语句 parsed = sqlparse.parse(sql) target_insert = "" for stmt in parsed: if stmt.get_type() == "INSERT": # 提取操作表名,自动过滤修饰符、空格 table_name = stmt.token_first(skip_ws=True, skip_cm=True).value.split()[-1].strip('`"\'') if table_name == "table1": target_insert = str(stmt).strip() break print(target_insert)
方案2:正则实现(无第三方依赖场景)
如果不能引入外部依赖,可以使用兼容字符串内分号的正则匹配:
import re pattern = r"INSERT INTO `?table1`?\s*\([^)]+\)\s*VALUES\s*(?:'[^']*'|\"[^\"]*\"|[^;])+;" match = re.search(pattern, sql, re.DOTALL) if match: target_insert = match.group(0).strip() print(target_insert)
正则逻辑:从INSERT INTO table1开始匹配,优先跳过单/双引号包裹的字符串内容,直到匹配到不在字符串内的语句结束分号为止,即可提取到完整的INSERT语句。
内容的提问来源于stack exchange,提问作者Javier Lopez Tomas
相关产品推荐
相关产品推荐

