【发布时间】:2014-03-25 08:10:06
【问题描述】:
% 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 在任何时候都有一致的视图,并且当 shell #2 没有时看到 id=29 记录,即使 /usr/bin/mysql 在 python 中做任何事情之前很久就打开了。此外,shell #1 会看到它刚刚插入的 id=29 记录及其当前连接。所以我怀疑我使用与 python mysql 连接器连接的方式有问题,但我已经没有想法了。
【问题讨论】:
-
这很有趣:在我发送 SELECT 语句之前在 shell#2 中添加一个 cnx.commit() (它只从数据库中读取,从不写入)也解决了这个问题。我错过了什么吗?我真的不想设置 autocommit=True,也不想在我的所有 SELECT 语句之前发送 COMMIT。
-
我应该添加:ENGINE=InnoDB
-
添加更多:/usr/bin/mysql 看到新记录,因为它有 autocommit=1。禁用它(设置 autocommit = 0)后,它也看不到新行。我怀疑默认隔离级别是问题所在:dev.mysql.com/doc/refman/5.1/en/innodb-consistent-read.html
-
请注意,MySQL-Python 不是 MySQL 连接器/Python。由于您导入了
mysql.connector,因此您使用的是后者。
标签: python mysql database mysql-python mysql-connector