如何使用 MySQLdb 从 Python 更改 SQL 隔离级别?

发布于 2024-11-01 18:14:33 字数 429 浏览 4 评论 0原文

我研究过的文档表明,对其他数据库执行此操作的方法是在查询中使用多个语句,a la:

>>> cursor = connection.cursor()
>>> cursor.execute("set session transaction isolation level read uncommitted; 
                    select stuff from table; 
                    set session transaction isolation level repeatable read;")

不幸的是,这样做不会产生任何结果,显然是 Python DB API(或者可能只是这个)它的实现?)不支持单个查询中的多个记录集。

过去有其他人在这方面取得过成功吗?

The documentation I've run across researching this indicates that the way to do it for other databases is to use multiple statements in your query, a la:

>>> cursor = connection.cursor()
>>> cursor.execute("set session transaction isolation level read uncommitted; 
                    select stuff from table; 
                    set session transaction isolation level repeatable read;")

Unfortunately, doing that yields no results, as apparently the Python DB API (or maybe just this implementation of it?) doesn't support multiple recordsets within a single query.

Has anyone else had success with this in the past?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

看轻我的陪伴 2024-11-08 18:14:33

我认为这不适用于 MySQLdb 驱动程序;你必须发出单独的查询:

cur = conn.cursor()
cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED")
cur.execute("SELECT @@session.tx_isolation")
print cur.fetchall()[0]
cur.execute("SELECT * FROM bar")
print cur.fetchall()
cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ")
cur.execute("SELECT @@session.tx_isolation")
print cur.fetchall()[0]

# output
('READ-UNCOMMITTED',)
(('foo',), ('bar',))
('REPEATABLE-READ',)

MySQLdb游标的execute()方法只能看到第一个查询到分号:

cur.execute("SELECT * FROM bar WHERE thing = 'bar'; SELECT * FROM bar")
print cur.fetchall()

# output
(('bar',),)

I don't think this works for the MySQLdb driver; you'll have to issue separate queries:

cur = conn.cursor()
cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED")
cur.execute("SELECT @@session.tx_isolation")
print cur.fetchall()[0]
cur.execute("SELECT * FROM bar")
print cur.fetchall()
cur.execute("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ")
cur.execute("SELECT @@session.tx_isolation")
print cur.fetchall()[0]

# output
('READ-UNCOMMITTED',)
(('foo',), ('bar',))
('REPEATABLE-READ',)

The MySQLdb cursor's execute() method only sees the first query up to the semicolon:

cur.execute("SELECT * FROM bar WHERE thing = 'bar'; SELECT * FROM bar")
print cur.fetchall()

# output
(('bar',),)
苏璃陌 2024-11-08 18:14:33
cur.executemany("SELECT * FROM bar WHERE thing = 'bar'; SELECT * FROM bar")
print cur.fetchall()

使用 cur.executemany 运行多个 sql 语句;分开了。

cur.executemany("SELECT * FROM bar WHERE thing = 'bar'; SELECT * FROM bar")
print cur.fetchall()

use cur.executemany to run multiple sql statements with ; separated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文