假设我们有这样一个简单的查询:
Select a.col1, b.col2 from tb1 as a inner join tb2 as b on tb1.col7 = tb2.col8;
结果应该是这样的:
tb1 col1
tb1 col7
tb2 col2
tb2 col8
我试着用一些python库来解决这个问题:
1)即使只使用sqlparse
提取表也可能是个大问题。例如this官方书籍根本不能正常工作。
2)使用正则表达式似乎很难实现。
3)但后来我发现了this,这可能会有帮助。但是问题是我无法连接到任何数据库并执行该查询。
有什么想法吗?
我正在处理一个类似的问题,并找到了一个更简单的解决方案,它似乎工作得很好。
代码改编自https://grisha.org/blog/2016/11/14/table-names-from-sql/
真的,这不是一件容易的事。您可以使用lexer(ply在本例中)并定义几个规则,以从字符串中获取多个标记。下面的代码为SQL字符串的不同部分定义这些规则,并将它们放回一起,因为输入字符串中可能有别名。结果,您将得到一个以不同表名作为键的字典(
result
)。相关问题 更多 >
编程相关推荐