在python中解析SQL查询

Cha*_*uri -1 python sql parsing

我需要在 python 中构建一个 mini-sql 引擎。所以我需要一个 sql-parser 并且我发现了 python-sqlparse 但我无法理解如何从 SQL 查询中提取列名或表名等。有人可以帮我解决这个问题。

Bul*_*lva 8

让我们检查 python sqlparse 文档:文档 - 入门

您可以在那里看到如何解析 sql 的示例。这是那里的东西:

1.首先你需要用parse方法解析sql语句:

sql = 'select * from "someschema"."mytable" where id = 1'
parsed = sqlparse.parse(sql)
Run Code Online (Sandbox Code Playgroud)

2. 现在你需要从解析中获取 Statement 对象:

stmt = parsed[0]
    '''(<DML 'select' at 0x9b63c34>,
 <Whitespace ' ' at 0x9b63e8c>,
 <Operator '*' at 0x9b63e64>,
 <Whitespace ' ' at 0x9b63c5c>,
 <Keyword 'from' at 0x9b63c84>,
 <Whitespace ' ' at 0x9b63cd4>,
 <Identifier '"somes...' at 0x9b5c62c>,
 <Whitespace ' ' at 0x9b63f04>,
 <Where 'where ...' at 0x9b5caac>)'''
Run Code Online (Sandbox Code Playgroud)

3.然后你可以用str()方法再次读取解析后的sql语句:

#all sql statement
str(stmt)
#only parts of sql statements
str(stmt.tokens[-1])
#so the result of last str() method is 'where id = 1'
Run Code Online (Sandbox Code Playgroud)

结果str(stmt.tokens[-1])'where id = 1'

如果你想要表的名称,你只需要写:

str(stmt.tokens[-3])
#result "someschema"."mytable"
Run Code Online (Sandbox Code Playgroud)

如果您需要列的名称,您可以调用:

str(stmt.tokens[2])
#result *, now it is operator * because there are not columns in this sql statements
Run Code Online (Sandbox Code Playgroud)

  • `sqlparse.parse(sql)[0].get_name()` 给出表名 (2认同)