我正在使用Python从.sql
文件执行一系列SQLite查询。似乎应该有一种很好的方法来检查查询的语法,以验证它们是否均正确编写并可以执行。这一点特别重要,因为这些查询将同时针对MySQL和SQLite,因此应捕获并标记任何特定于MySQL的语法。
当然,我可以只执行查询并查找异常。但是似乎应该有一个更好的方法。
python大神给出的解决方案
我已经解决了创建内存数据库并执行我感兴趣的查询的问题。但是,以下代码示例非常慢,我将继续寻找更好的解决方案。另外,我知道以下代码中的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()
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
Python pytz时区函数返回的时区为9分钟 - python由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…
如何打印浮点数的全精度[Python] - python我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…
查找字符串中的行数 - python我正在创建一个python电影播放器/制作器,我想在多行字符串中找到行数。我想知道是否有任何内置函数或可以编写代码的函数来做到这一点:x = """ line1 line2 """ getLines(x) python大神给出的解决方案 如果换行符是'\n',则nlines …