【问题标题】:cursor fetch wrong records from mysql游标从mysql中获取错误的记录
【发布时间】:2012-04-03 15:08:39
【问题描述】:
>>> _cursor.execute("select * from bitcoin.test where id > 34") 1L >>> _cursor.fetchall() ({'priority': 1L, 'default': 0, 'id': 35L, 'name': 'chinanet'},) >>> _cursor.execute("select * from bitcoin.test where id > 34") 1L >>> _cursor.fetchall() ({'priority': 1L, 'default': 0, 'id': 35L, 'name': 'chinanet'},) >>>

第一次,我运行 cursor.execute 和 cursor.fetchall,我得到了正确的结果。

在我第二次运行执行和 fetchall 之前

我将数据插入 id 为 36 的 mysql,我也在 mysql 中运行 commit 命令

但是 cursor.execute/fetchall 只能获取之前没有新数据的数据

【问题讨论】:

  • 第二次插入是怎么做的?来自 Python 还是 MySQL shell?

标签: python mysql-python


【解决方案1】:

我猜你正在使用 InnoDB。这是 InnoDB 事务的默认设置。

可重复阅读

这是 InnoDB 的默认隔离级别。对于一致的读取, 与 READ COMMITTED 隔离有一个重要区别 level:同一个事务中的所有一致性读 由第一次读取建立的快照。这个约定意味着如果 您在同一个文件中发出几个普通(非锁定)SELECT 语句 事务,这些 SELECT 语句也是一致的 对彼此。请参阅第 13.2.8.2 节,“一致的非锁定读取”。

我尚未测试,但通过在当前连接上发出 commit() 或创建新连接来强制 MySQLdb 启动新事务可能会解决问题。

【讨论】:

  • 谢谢。你说的对。 fetchall 之后,运行提交就可以了。或 SET TRANSACTION ISOLATION LEVEL READ COMMITTED 也可以。
【解决方案2】:

我试过了,得到了结果

import MySQLdb


conn = MySQLdb.connect('localhost', 'test', 'test', db='test')

cur = conn.cursor()

result = cur.execute("select * from users where id > 7")

print "RESULT :", result
print "DATA :", cur.fetchall()


cur.execute("insert into users(day) values('2012-03-15')")
conn.commit()

result = cur.execute("select * from users where id > 7")

print "RESULT :", result
print "DATA :", cur.fetchall()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 2023-03-24
    • 1970-01-01
    • 2019-06-10
    相关资源
    最近更新 更多