# apply only to "from ... where" situation regex = r"(\bFROM\s)+(`\w+`,?\s?)+(\s+\w?\sWHERE)+" # Compile match pattern pattern = re.compile(regex)
res = set() # The file path is changed according to the situation with open("./log.txt", "r") as f: whileTrue: line = f.readline().replace("\n", "") ifnot line: break # Just get the table name(or tables' name); # Because of the multi-table case, group(0) is used to get the entire matching string find = re.search(regex, line).group(0) if find: find = find.replace("FROM ", "").replace(" WHERE", "") # Multi-table situation: from table1, table2, table3 ... where if","in find: names = find.split(", ") for name in names: res.add(name.replace("`", "")) else: res.add(find.replace("`", ""))
regex = r"(SQL:)(.+)(\sCost)" # Compile match pattern pattern = re.compile(regex)
res = set() try: # The file path is changed according to the situation with open("./log.txt", "r") as f: whileTrue: line = f.readline().replace("\n", "") ifnot line: break # Parenthesis is used for group capture and the 2th group is the SQL statement find = pattern.search(line) if find: res.add(find.group(2)) except Exception as e: print("Reason:", e)
try: with open("./sql_statements.txt", "a") as f: for sql in res: f.write(sql) except Exception as e: print("Reason:", e)
意外状况
要筛选出像这样的语句:
1 2 3
SELECT`id`FROM`form_element`WHERE (id = '13126454') SELECT`id`FROM`form_element`WHERE (id = '13126418') SELECT`id`FROM`form_element`WHERE (id = '13126429')