用后引号封装复杂的mysql插入

时间:2014-11-19 23:21:24

标签: mysql regex sed

我已经导出了一些sql语句,现在需要重放它们。当我将它发送到mysql时会出现问题,其中实际的Java代码包含在VALUES中。此代码包括反斜杠,引号,双引号 - 有时会导致mysql错误地解释转义和引用:

INSERT INTO sonar.snapshot_sources(ID, SNAPSHOT_ID, DATA) VALUES (267, 420, 
'package com.company.gateway.dl.util    
"((\''|\")*)(stuff|moreStuff)((\''|\")*):((\''|\")*)([0-9]+)((\''|\")*)";
');

上面不是全文,但这里引用的位导致插入失败。解决方法是将复杂文本值括在后引号中,例如

INSERT INTO sonar.snapshot_sources(ID, SNAPSHOT_ID, DATA) VALUES (267, 420, 
`'package com.company.gateway.dl.util
"((\''|\")*)(stuff|moreStuff)((\''|\")*):((\''|\")*)([0-9]+)((\''|\")*)"; 
'`);

我的问题是,我怎样才能准确地将这些语句添加回来以封装所需的语句?我想用'' package和')替换'包;用'`);结束括号似乎是最复杂的,因为更多的语句将与此匹配。

1 个答案:

答案 0 :(得分:0)

以下python脚本可以帮助您。该脚本将读取sql转储文件并向匹配的正则表达式添加反引号并将其打印到输出文件。输入文件和输出文件应作为命令行参数给出。

#!/usr/bin/env python3


import re
import os
import sys

if len(sys.argv) < 3:
    print('Provide input and output file to begin processing')
    sys.exit(1)
else:
    if not os.path.isfile(sys.argv[1]):
        print('Input file does not exit')
        sys.exit(1)

ifile = sys.argv[1]
ofile = sys.argv[2]

# Compiling the regex
rex = re.compile(r"""(INSERT[\s\S]+?)('package[\s\S]+?')(\);)""")

# Reading the file as a string
dataFile = open(ifile, 'r').read()
fp = open(ofile, 'w')

# Substituting it
print(re.sub(rex, r'\1`\2`\3', dataFile), end='', file=fp)

fp.close()

输出

INSERT INTO sonar.snapshot_sources(ID, SNAPSHOT_ID, DATA) VALUES (267, 420, 
`'package com.company.gateway.dl.util    
"((\''|\")*)(stuff|moreStuff)((\''|\")*):((\''|\")*)([0-9]+)((\''|\")*)";
'`);