python转下一行,Python从当前行或下一行提取信息

该博客演示了如何使用Python的sqlparse模块读取sqlExamples.sql文件,并进行SQL语句的标准化格式化以及提取列名。通过sqlparse.format()函数重新格式化SQL,将所有语句转换为大写并整理缩进。此外,还展示了如何直接使用解析器提取SQL语句中的列名。
摘要由CSDN通过智能技术生成

使用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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值