使用Python和SQLite验证SQL查询语法

时间:2015-02-26 14:30:04

标签: python sqlite

我正在使用Python从.sql文件执行一系列SQLite查询。似乎应该有一个很好的方法来检查查询的语法,以验证它们都是正确编写并将执行。这一点尤为重要,因为这些查询都适用于MySQL和SQLite,因此应该捕获并标记任何特定于MySQL的语法。

当然,我可以执行查询并查找异常。但似乎应该有更好的方法。

2 个答案:

答案 0 :(得分:1)

我已经决定创建一个内存数据库并执行我感兴趣的查询。但是,以下代码示例非常慢,我将继续寻找更好的解决方案。另外,我在下面的代码中知道SQL注入攻击的漏洞,但这不是我现在关注的问题。

import sqlite3

# open the SQL file and read the contents
f_contents = open("example.sql").read()

# Use regexes to split the contents into individual SQL statements.
# This is unrelated to the issues I'm experiencing, show I opted not
# to show the details. The function below simply returns a list of
# SQL statements
stmnt_list = split_statements(f_contents)

temp_db = sqlite3.connect(":memory:")

good_stmnts = []    # a list for storing all statements that executed correctly
for stmnt in stmnt_list:
    # try executing the statement
    try:
        temp_db.execute(stmnt)
    except Exception as e:
        print("Bad statement. Ignoring.\n'%s'" % stmnt)
        continue
    good_stmnts.append(stmnt)

temp_db.close()

答案 1 :(得分:0)

使用sqlparse模块,您应该能够尝试解析每个语句,而不必执行它并回滚。从理论上讲,这将更有效:

import sqlparse

# open the SQL file and read the contents
f_contents = open("example.sql").read()

# Use regexes to split the contents into individual SQL statements.
# This is unrelated to the issue
stmnt_list = split_statements(f_contents)

good_stmnts = []    # statements that executed correctly
for stmnt in stmnt_list:
    try:
        sqlparse.parse(stmnt)
        good_stmnts.append(stmnt)
    except sqlparse.exceptions.SQLParseError:
        print("Bad statement. Ignoring.\n'%s'" % stmnt)

我也进行了一些不相关(和可选)的更改:

  • good_stmnts附加在try块& rm continue
  • 仅抓住SQLParseError