使用sqlparse模块。在> python setup.py install

然后创建测试文件sqlExamples.sql:

^{pr2}$

然后让我们看看解析器是否可以帮助我们。。

这不是很有效的脚本,它是为学习而写的:

import sqlparse
print " "
print "loading the file into a string"
print " "
with open ("sqlExamples.sql", "r") as myfile:
sql = myfile.read()
print sql
print " "
print "Example 1: using the parser to reformat SQL to a standardized format"
print " "
formattedSQL = sqlparse.format(sql, reindent=True, keyword_case='upper')
print formattedSQL
print " "
print "Example 1.A: reformatting statements, to single lines, for string analysis"
print " "
words = " ".join(formattedSQL.split()).replace('; ', ';\n')
print words
print " "
print "Example 2: using the parser more directly, to extract coloumns"
print " "
parsed = sqlparse.parse(sql)
coloumns = []
tables = []
for SQL in parsed:
#For my test cases, the name of the statement and the affected table is the same thing..
if( SQL.get_name() not in tables):
tables.append( SQL.get_name() )
#for debugging print token list:
for token in SQL.tokens:
if token.is_whitespace():
continue
if "SELECT" in SQL.get_type() and token.is_group():
cols = token.value.split(",")
for col in cols:
if col.strip() not in coloumns:
coloumns.append(col.strip())
break
print "tables:" + str(tables)
print "cols:" + str(coloumns)