PythonSQLite3不能生成表视图

2024-10-01 11:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

通过python,我打开了一个SQLite数据库,并尝试访问一个表视图的视图。不幸的是,我收到了一条错误消息。下面的Python代码演示了这个问题:

import sqlite3

conn = sqlite3.connect("test.db")
mydb = conn.cursor()

mydb.execute("CREATE TABLE TestTbl (MRTarget_id int, Fullmodel text)")
mydb.execute("CREATE TABLE TestTbl2 (Other_id int, Othermodel text)")

mydb.execute("CREATE VIEW TestView AS SELECT m.ROWID, m.MRTarget_id, m.Fullmodel, t.Othermodel FROM TestTbl m, TestTbl2 t")
mydb.execute("CREATE VIEW TestView2 AS SELECT m.Fullmodel, m.Othermodel FROM TestView m")

mydb.close()

Python在尝试创建TestView2之后会显示错误“sqlite3.OperationalError:no-this column:m.Fullmodel”。但是,从Sqlite3提示符可以毫无问题地执行上面的SQL语句。由于我的数据库包含表视图,我想知道是否根本不可能通过Python以编程方式访问这些视图。在


Tags: 视图id数据库execute错误createtableconn
2条回答

我也遇到了同样的问题,我找到了解决办法。我相信您的问题是在初始视图“TestView”中,属性名实际上是m.ROWIDm.Fullmodel等,而不是{},Fullmodel

通过sqlitemanager随意查看视图不会发现每个字段名前面附加的m.。如果运行Pragma查询PRAGMA table_info TestView,则会显示属性扩展名。在

因此,将TestView创建查询更改为

CREATE VIEW TestView AS 
SELECT m.ROWID as ROWID, m.MRTarget_id as MRTarget_id,... etc

您的第二个Create View查询应该成功运行——至少在我的应用程序中是这样。在

你的代码很适合我。在

您可以尝试在创建第一个视图和第二个视图之间提交:

conn.commit()

相关问题 更多 >