python - 使用 python 添加表时出现 sqlite3 错误,但使用 SQLite 的 DB Browser 时没有
问题描述
在包括 StackOverflow 在内的一些论坛中讨论的问题似乎相似但不完全相同,因此它们对我下面的问题没有帮助。
我可以使用 DB Browser for Sqlite 或 Python 将一系列表添加到 sqlite3 数据库而不会出错,除非在一种情况下,DB Browser 工作正常但 python 失败。我的目标是创建一个自动顺序运行 sqlite3 脚本的 python 程序。
根据报错信息,python挂机的地方是在“AS”附近的以下脚本(同一个文件中的几个顺序“create table”脚本之一):
DROP TABLE if EXISTS SheetGoods;
CREATE TABLE SheetGoods (
SheetId INTEGER PRIMARY KEY,
ItemNo INTEGER,
ItemCategory TEXT,
ItemName TEXT,
SheetName TEXT,
Width REAL,
Height REAL,
Depth REAL,
Thickness REAL,
Area REAL GENERATED ALWAYS AS ((Width * Height)/144) STORED,
/* SYNTAX for line above similar to: column INT GENERATED ALWAYS AS (a*abs(b)) VIRTUAL or STORED
Consider putting this formula into a Python script and update table with python output*/
for_Pricing INTEGER,
for_Order_List INTEGER,
Comments TEXT,
FOREIGN KEY(ItemNo) REFERENCES Items(ItemId)
);
调用上述 sqlite3 查询的 Python 脚本适用于我的所有表,除了这个实例。如果我在 Column: "Area REAL" 之后注释掉生成列的末尾(即:以下内容被省略 - "GENERATED ALWAYS AS ((Width * Height)/144) STORED )" 那么 python 不会挂起。我一直无法找到一种方法来解决 Python 使用这种语法的问题。
蟒蛇代码是:
# runNewProjectScript.py
import sqlite3
newDbName = "Johnston.db"
try:
sqliteConnection = sqlite3.connect(newDbName)
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
# the following was advice from sqlite3 website. But it seems there is issues.
cursor.execute('pragma foreign_keys=ON')
with open('C:\myPy38\sqlite\sqLiteCabTest\cabPricingScripts\cabPricing.sql', 'r') as sqlite_file:
sql_script = sqlite_file.read()
cursor.executescript(sql_script)
print("SQLite script executed successfully")
cursor.close()
except sqlite3.Error as error:
print("Error while executing sqlite script", error)
finally:
if (sqliteConnection):
sqliteConnection.close()
print("sqlite connection is closed")
错误信息如下:
$ python runNewProjectScript.py
Successfully Connected to SQLite
Error while executing sqlite script near "AS": syntax error
sqlite connection is closed
解决方案
推荐阅读
- c++ - C++ 键盘钩子 CTRL 键卡住
- sql - 从 PostgreSQL 中的 json 列表中删除键
- android - 应用程序因在后台频繁刷新而耗尽电池电量
- asp.net - Asp.net MVC 中的自动完成文本框
- dynamics-crm - 始终使用通配符的 Dynamics 365 全局搜索和查找
- javascript - select2.js 获取事件目标
- php - PHPPROBID 付款
- android - 运行 Android 9 及更低版本的设备上的 AndroidX BiometricPrompt
- python - Python:如何使用函数增加全局变量
- javascript - 当用户从下拉列表中选择值时,在文本区域中显示数据库值