我有一个 sql nodata 转储,我需要通过它并替换每个创建表查询的引擎部分。我被卡住的地方是我需要在每个字符串中提到表名,我用相应的表替换
假设文件如下
CREATE TABLE `tablename1` (
-- #columns and keys
) ENGINE=InnoDB AUTO_INCREMENT=5075 DEFAULT CHARSET=utf8;
CREATE TABLE `tablename2` (
-- #columns and keys
) ENGINE=something AUTO_INCREMENT=55 DEFAULT CHARSET=latin1;
期望的结果是:
CREATE TABLE `tablename1` (
-- #columns and keys
) ENGINE=-myreplacedstring/tablename1; -- #table name 1 is appended to this line
CREATE TABLE `tablename2` (
-- #columns and keys
) ENGINE=myreplacedstring/tablename2; -- #table name 2 is appended to this line
我试过
fin = open('dump.sql','r')
filedata = fin.read()
fin.close()
newdata = re.sub('(?<=ENGINE).*;', '-myreplacedstring-', filedata)
fout = open('fed_dump.sql','w')
fout.write(newdata)
fout.close()
但这只会用固定字符串替换字符串,无论它是哪个表。
我还尝试逐行处理,以便每次通过时都能获取表名,但我不知道如何继续。
with open('dump.sql') as infile, open('dump_fed.sql', 'w') as outfile:
for line in infile:
#tablename= if line contains create table, update tablename, else do nothing
line = re.sub('(?<=ENGINE).*;', '-myreplacedstring-'+tablename, line)
outfile.write(line)
我被困在如何将每个表的表名放入替换的字符串中。任何帮助表示赞赏。