mysql连接器不显示插入的结果

2024-04-20 08:51:03 发布

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

% sudo yum info MySQL-python.x86_64
Loaded plugins: priorities, update-motd, upgrade-helper
Installed Packages
Name        : MySQL-python
Arch        : x86_64
Version     : 1.2.3
Release     : 0.3.c1.1.9.amzn1

外壳1:

^{pr2}$

外壳2:

% python
Python 2.6.9 (unknown, Oct 29 2013, 19:58:13)
[GCC 4.6.3 20120306 (Red Hat 4.6.3-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector as mysqlconn
>>> cnx = mysqlconn.connect(...)
>>> cur = cnx.cursor()
>>> cur.execute("select id, name from sometable where id = 28")
>>> cur.fetchall()
[(28, u'28')]

到目前为止还不错。以下是令人惊讶的事情:

外壳1:

>>> cur.close()
True
>>> cur = cnx.cursor()
>>> cur.execute("insert into sometable(id, name) values(%s, %s)", (29, "29"))
>>> cnx.commit()
>>>

外壳2:

>>> cur.close()
True
>>> cur = cnx.cursor()
>>> cur.execute("select id, name from sometable where id = 29")
>>> cur.fetchall()
[]
>>>

由于某些原因,具有当前连接的shell#2看不到新插入的id=29的记录。在shell 2中创建一个新的连接可以解决这个问题,但显然我不想这样做。我应该注意到,/usr/bin/mysql在任何时候都有一个一致的视图,当shell#2没有的时候,即使在使用python之前很久就打开了/usr/bin/mysql,也可以看到id=29记录。另外,shell#1会看到id=29记录,它刚刚用当前连接插入。所以我怀疑我使用pythonmysql连接器连接的方式有问题,但是我已经没有主意了。在


Tags: nameidexecute记录mysqlshell外壳select
1条回答
网友
1楼 · 发布于 2024-04-20 08:51:03

MySQL的默认隔离级别是REPEATABLE READ。如果在shell#1中插入数据并发出COMMIT,则数据将仅对提交后新启动的事务可用。shell 2中的事务仍在进行中,不会看到新数据。在

您可以通过在服务器(或会话)上设置默认事务隔离级别来更改此设置,或者更好地为当前事务设置隔离级别。在

对于MySQL Connector/pythonv1.1,使用^{} method设置隔离很容易。在shell 2中,请执行以下操作:

>>> cnx = mysql.connector.connect(...)
>>> cnx.start_transaction(isolation_level='READ COMMITTED')
>>> cur = cnx.cursor()
>>> cur.execute("select id, name from sometable where id = 29")
>>> cur.fetchall()
# Do something in shell #1 and commit there
>>> cur.execute("select id, name from sometable where id = 29")
>>> cur.fetchall()
[(28, u'28')]

start_transaction不是PEP-249,但您可以简单地执行SQL语句^{}或设置会话变量{}。但我认为这个方法更容易。在

相关问题 更多 >