栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从SQL查询中提取表名和列名?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从SQL查询中提取表名和列名?

确实,这不是一件容易的事。您可以使用词法分析器(在此示例中为ply)并定义一些规则以从字符串中获取多个标记。以下代码为SQL字符串的不同部分定义了这些规则,并将它们放在一起,因为输入字符串中可能会有别名。结果,您将获得一个

result
以不同表名作为键的字典()。

import ply.lex as lex, retokens = (    "TABLE",    "JOIN",    "COLUMN",    "TRASH")tables = {"tables": {}, "alias": {}}columns = []t_TRASH = r"Select|on|=|;|s+|,|t|r"def t_TABLE(t):    r"froms(w+)sass(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 tdef t_JOIN(t):    r"inners+joins+(w+)s+ass+(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 tdef 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 tdef t_error(t):    raise TypeError("Unknown text '%s'" % (t.value,))    t.lexer.skip(len(t.value))# here is where the magic startsdef 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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/648054.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号