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

Bry*_*ant 5 python sqlite

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

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

Bry*_*ant 4

我已经决定创建一个内存数据库并执行我感兴趣的查询。然而,下面的代码示例非常慢,我将继续寻找更好的解决方案。另外,我知道以下代码中存在 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()
Run Code Online (Sandbox Code Playgroud)