首页 > 解决方案 > 使用 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

标签: pythonsqlite

解决方案


SQLite 网站说:

SQLite 版本 3.31.0 (2020-01-22) 添加了生成的列支持。

我找不到 Python 模块使用的 SQLite 版本,但由于pysqlitesqlite3的 github 存储库自 2016 年以来没有更新,因此我不会对它使用旧版本感到惊讶。

换句话说,当您使用 Python 时,您实际上使用的 SQLite 引擎不知道生成的列。除了不使用该功能之外,我无法想象任何解决方法。


推荐阅读