以下脚本在UPDATE命令中引发以下异常。我认为这个简单的UPDATE命令应该发生的事情是db_2.foo.bar的值应该从1加倍到2.我的猜测是我在UPDATE语句中有一些微妙的语法错误(或者Python上的一个错误)或sqlite3级别);但是,我仔细阅读了sqlite3文档 - 尤其是“UPDATE”和“expression”页面 - 并且没有看到我做错了什么。
db_1.foo_bar= (1,)
Traceback (most recent call last):
File "try2.py", line 29, in <module>
db_2.execute( 'UPDATE foo SET bar = bar + db_1.foo.bar WHERE rowid = db_1.foo.rowid' )
sqlite3.OperationalError: no such column: db_1.foo.bar
有任何建议或解决方法吗?
import sqlite3
# Create db_1, populate it and close it:
open( 'db_1.sqlite', 'w+' )
db_1 = sqlite3.connect( 'db_1.sqlite' )
db_1.execute( 'CREATE TABLE foo(bar INTEGER)' )
db_1.execute( 'INSERT INTO foo (bar) VALUES (1)' )
db_1.commit()
db_1.close()
# Create db_2:
open( 'db_2.sqlite', 'w+' )
db_2 = sqlite3.connect( 'db_2.sqlite' )
db_2.execute( 'CREATE TABLE foo(bar INTEGER)' )
# Attach db_1 to db_2 connection:
db_2.execute( 'ATTACH "db_1.sqlite" AS db_1' )
# Populate db_2 from db_1:
db_2.execute( 'INSERT INTO foo SELECT ALL * FROM db_1.foo' )
# Show that db_1.foo.bar exists:
cur_2 = db_2.cursor()
cur_2.execute( 'SELECT bar from db_1.foo' )
for result in cur_2.fetchall():
print 'db_1.foo_bar=', result
# However, the following claims that db_1.foo.bar does not exist:
db_2.execute( 'UPDATE foo SET bar = bar + db_1.foo.bar WHERE rowid = db_1.foo.rowid' )
db_2.execute( 'DETACH db_1')
db_2.commit()
db_2.close()
答案 0 :(得分:1)
要使用其他表中的值更新foo
,可以使用嵌套的SELECT表达式。请注意,foo.rowid
引用外部表的rowid,而t.rowid
引用内部表的rowid:
cur_2.execute( '''\
UPDATE foo SET bar = bar +
IFNULL( (SELECT t.bar
FROM db_1.foo AS t
WHERE foo.rowid = t.rowid), 0)''' )
为了测试正确的rowids
确实匹配在一起,我稍微修改了您的代码,因此rowids
的{{1}}与db_1.foo
rowids
不匹配1}}:
db_2.foo
请注意import sqlite3
# Create db_1, populate it and close it:
open( 'db_1.sqlite', 'w+' )
db_1 = sqlite3.connect( 'db_1.sqlite' )
db_1.execute( 'CREATE TABLE foo(bar INTEGER)' )
db_1.execute( 'INSERT INTO foo (rowid,bar) VALUES (2,1)' )
db_1.execute( 'INSERT INTO foo (rowid,bar) VALUES (3,2)' )
db_1.commit()
db_1.close()
# Create db_2:
open( 'db_2.sqlite', 'w+' )
db_2 = sqlite3.connect( 'db_2.sqlite' )
cur_2 = db_2.cursor()
cur_2.execute( 'CREATE TABLE foo(bar INTEGER)' )
# Attach db_1 to db_2 connection:
cur_2.execute( 'ATTACH "db_1.sqlite" AS db_1' )
# Populate db_2 from db_1:
cur_2.execute( 'INSERT INTO foo SELECT * FROM db_1.foo' )
的{{1}}为1和2:
rowids
请注意foo
的{{1}}为2和3:
cur_2.execute( 'SELECT rowid,bar from foo' )
for result in cur_2.fetchall():
print('foo: {0}'.format(result))
# foo: (1, 1)
# foo: (2, 2)
UPDATE之后,rowid = 1的行没有改变, 而rowid = 2的行已更新。
rowids
答案 1 :(得分:0)
嗯...问题很可能是我正在查看3.7.3文档,而我的安装版本是3.6.16。调查。