在python sqlite3中使用保存点

前端之家收集整理的这篇文章主要介绍了在python sqlite3中使用保存点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在尝试将保存点与python 2.6中内置的sqlite3模块一起使用.每次我尝试释放或回滚保存点时,我总是收到一个OperationalError:没有这样的保存点.我错过了什么?

python version: 2.6.4 (r264:75821M,Oct 27 2009,19:48:32) 
[GCC 4.0.1 (Apple Inc. build 5493)]
Pysqlite version: 2.4.1
sqlite3 version: 3.6.11

Traceback (most recent call last):
  File "spDemo.py",line 21,in sqlite3.OperationalError: no such savepoint: spTest

从这段代码

import sys
import sqlite3

print 'python version:',sys.version
print 'Pysqlite version:',sqlite3.version
print 'sqlite3 version:',sqlite3.sqlite_version
print

conn = sqlite3.connect('db_spDemo.db')
conn.isolation_level = "DEFERRED"

with conn:
    conn.execute("create table example (A,B);")

with conn:
    conn.execute("insert into example values (?,?);",(0,200))

    conn.execute("savepoint spTest;")
    conn.execute("insert into example values (?,(1,201))
    conn.execute("insert into example values (?,(2,202))
    conn.execute("release savepoint spTest;")

    conn.execute("insert into example values (?,(5,205))
最佳答案
这似乎是sqlite3模块如何与该隔离级别一起运行的结果.

这有效,请注意两个变化:

import sys
import sqlite3

print 'python version:',sqlite3.sqlite_version
print

conn = sqlite3.connect('shane.sqlite')
conn.isolation_level = None  # CHANGED

with conn:
    conn.execute("create table example (A,202))
    conn.execute("rollback to savepoint spTest;")  # CHANGED

    conn.execute("insert into example values (?,205))

输出

$python shane-sqlite3.py && sqlite3 shane.sqlite 'select * from example;'
python version: 2.6.2 (release26-maint,Apr 19 2009,01:56:41) 
[GCC 4.3.3]
Pysqlite version: 2.4.1
sqlite3 version: 3.6.10

0|200
5|205

这是一个令人不满意的答案,我没有在sqlite3模块文档中看到任何相关内容(我也没有尝试查看源代码).但我希望它能帮助您找到正确的方向.

猜你在找的Python相关文章