python获取数据库列名_如何从sql查询中提取表名和列名?

真的,这不是一件容易的事。您可以使用lexer(ply在本例中)并定义几个规则,以从字符串中获取多个标记。下面的代码为SQL字符串的不同部分定义这些规则,并将它们放回一起,因为输入字符串中可能有别名。结果,您将得到一个以不同表名作为键的字典(result)。import ply.lex as lex, re

tokens = (

"TABLE",

"JOIN",

"COLUMN",

"TRASH"

)

tables = {"tables": {}, "alias": {}}

columns = []

t_TRASH = r"Select|on|=|;|\s+|,|\t|\r"

def t_TABLE(t):

r"from\s(\w+)\sas\s(\w+)"

regex = re.compile(t_TABLE.__doc__)

m = regex.search(t.value)

if m is not None:

tbl = m.group(1)

alias = m.group(2)

tables["tables"][tbl] = ""

tables["alias"][alias] = tbl

return t

def t_JOIN(t):

r"inner\s+join\s+(\w+)\s+as\s+(\w+)"

regex = re.compile(t_JOIN.__doc__)

m = regex.search(t.value)

if m is not None:

tbl = m.group(1)

alias = m.group(2)

tables["tables"][tbl] = ""

tables["alias"][alias] = tbl

return t

def t_COLUMN(t):

r"(\w+\.\w+)"

regex = re.compile(t_COLUMN.__doc__)

m = regex.search(t.value)

if m is not None:

t.value = m.group(1)

columns.append(t.value)

return t

def t_error(t):

raise TypeError("Unknown text '%s'" % (t.value,))

t.lexer.skip(len(t.value))

# here is where the magic starts

def mylex(inp):

lexer = lex.lex()

lexer.input(inp)

for token in lexer:

pass

result = {}

for col in columns:

tbl, c = col.split('.')

if tbl in tables["alias"].keys():

key = tables["alias"][tbl]

else:

key = tbl

if key in result:

result[key].append(c)

else:

result[key] = list()

result[key].append(c)

print result

# {'tb1': ['col1', 'col7'], 'tb2': ['col2', 'col8']}

string = "Select a.col1, b.col2 from tb1 as a inner join tb2 as b on tb1.col7 = tb2.col8;"

mylex(string)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值