【发布时间】:2019-03-01 14:20:55
【问题描述】:
我无法理解 python 的 sqlite3 模块的光标对象的行为。据我了解,游标对象的行为类似于在数据结构上保持“视图”的迭代器。现在,我认为这有两种表现方式:
1) 在执行时,与SELECT * 语句匹配的数据库状态与期货更改保持分离
2) 在执行时,与SELECT * 语句匹配的数据库状态只是底层可变数据的视图。 IE。执行 for ... in cur 行后,就会进行惰性求值。
但显然情况并非如此,请参阅下面的脚本和输出。执行这个脚本时,为什么UPDATE命令没有并入游标,而INSERT是?总是使用result = list(cur.execute(...)) 会更好吗?
#!/usr/bin/env python3
import sqlite3
con = sqlite3.connect("db.sqlite")
con.execute("""CREATE TABLE IF NOT EXISTS `table` (
`id` INTEGER UNIQUE,
`name` TEXT,
PRIMARY KEY(`id`)
);""")
con.execute("INSERT INTO `table` VALUES (1, 'smith')")
con.execute("INSERT INTO `table` VALUES (2, 'mia')")
con.commit()
print("in db: (1, smith), (2, mia)")
### Querying the table
cur = con.cursor()
cur.execute("SELECT * FROM `table`")
### Changing the table
print("altering table: add (3, kim), change (1, smith) to (1, james)")
con.execute("UPDATE `table` SET name='james' where id=1")
con.execute("INSERT INTO `table` VALUES (3, 'kim')")
con.commit()
print()
print("1) expect immutable: (1, smith), (2, mia)")
print("2) expect mutable: (1, james), (2, mia), (3, kim)")
print()
print("But got: ")
for row in cur: print(row)
输出
in db: (1, smith), (2, mia)
altering table: add (3, kim), change (1, smith) to (1, james)
1) expect immutable: (1, smith), (2, mia)
2) expect mutable: (1, james), (2, mia), (3, kim)
But got:
(1, 'smith')
(2, 'mia')
(3, 'kim')
平台
- Ubuntu 18.10 x64
- Python 3.6.7(默认,2018 年 10 月 22 日,11:32:17)
- sqlite3.version = '2.6.0'
【问题讨论】:
-
我明白了:(1, u'james') (2, u'mia') (3, u'kim')。我在 Python 2.7 windows 7 上
-
真的吗?奇怪的是,我刚刚再次检查了我提供的源代码。徒劳无功。你用的是什么平台?我在 python3.6.7 ubuntu 18.10
标签: python sqlite database-cursor