让我们检查 python sqlparse 文档:文档 - 入门 https://sqlparse.readthedocs.io/en/latest/intro/#getting-started
您可以看到如何解析 sql 的示例。这就是那里的东西:
1.首先需要使用parse方法解析sql语句:
sql = 'select * from "someschema"."mytable" where id = 1'
parsed = sqlparse.parse(sql)
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>)'''
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'
的结果str(stmt.tokens[-1])
那么就是'where id = 1'
如果你想要表的名称,你只需要写:
str(stmt.tokens[-3])
#result "someschema"."mytable"
如果您需要列的名称,可以调用:
str(stmt.tokens[2])
#result *, now it is operator * because there are not columns in this sql statements