繁体   English   中英

判断一个sql语句是否以SELECT字开头

[英]Determine if a sql statement starts with the word SELECT

我正在尝试对输入的 SQL 字符串进行一些基本验证。 我想确保查询的第一个单词是SELECT否则我会引发错误。 这里有些例子:

1) yes
SELECT * FROM table

2) no
# SELECT * FROM table;
DROP TABLE table;

3) no
   /* SELECT * FROM 
   TABLE */ DROP TABLE table;

4) yes
# here is a comment
SELECT * FROM table

5) yes
/* here is a
comment */ SELECT * FROM table

以及其他各种。 也许这更像是一个正则表达式解决方案或 string.replace。 但是什么是查看是否输入了 SQL SELECT 语句的好方法?

尽管可以使用正则表达式和其他基于文本的技巧,但正确的 SQL 解析器(例如https://pypi.org/project/sqlparse/)可行的方法。 例如:

import sqlparse
statements = sqlparse.parse(my_evil_sql)
for statement in statements:
  if statement.get_type() != "SELECT":
    raise Exception("Non-select statement encountered!")

请注意, get_type()忽略语句开头的空格和注释。

我会为这项工作使用合适的工具 - sqlparse SQL parser ,获取第一个语句对象并检查它是否为SELECT类型:

In [1]: import sqlparse

In [2]: queries = [
   ...:     "SELECT * FROM table",
   ...:     """
   ...:     # SELECT * FROM table;
   ...:     DROP TABLE table;
   ...:     """,
   ...:     """/* SELECT * FROM 
   ...:    TABLE /* DROP table table;""",
   ...:    """
   ...:    # here is a comment
   ...:    SELECT * FROM table
   ...:    """
   ...: ]

In [3]: def is_select(query):
             first_statement = next((token for token in sqlparse.parse(query) if isinstance(token, sqlparse.sql.Statement)), None) 
             if first_statement:
                 return first_statement.get_type() == 'SELECT'

In [4]: for query in queries:
    ...:     print(query, is_select(query))

    SELECT * FROM table 
    True

    # SELECT * FROM table;
    DROP TABLE table;
    False

   /* SELECT * FROM 
   TABLE /* DROP table table; 
   False

   # here is a comment
   SELECT * FROM table
   True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM