% 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:
% 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("insert into sometable(id, name) values(%s, %s)", (28, "28"))
>>> cnx.commit()
外壳#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 在任何时候都有一个一致的 View ,并且在 shell #2 没有时看到 id=29 记录,即使在 python 中执行任何操作之前很久就打开了/usr/bin/mysql 。此外,shell #1 看到它刚刚插入当前连接的 id=29 记录。所以我怀疑我使用 python mysql 连接器连接的方式有问题,但我的想法已经用完了。
最佳答案
MySQL 的默认隔离级别是 REPEATABLE READ .如果您在 shell #1 中插入数据并发出 COMMIT,则数据将仅可用于此 COMMIT 之后新启动的事务。 shell #2 中的事务仍在进行中,不会看到新数据。
您可以通过在服务器(或 session )上设置默认事务隔离级别来更改此设置,或者为当前事务设置隔离可能更好。
使用 MySQL Connector/Python v1.1,使用 MySQLConnection.start_transaction()
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 语句 START TRANSACTION ISOLATION LEVEL READ COMMITTED
或者设置 session 变量 tx_isolation
。但我认为 start_transaction
方法使它更容易。
关于python - mysql 连接器不显示插入的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21974627/