【问题标题】:PyMySQL selecting data in loop returns not all recordsPyMySQL 在循环中选择数据不会返回所有记录
【发布时间】:2016-11-30 06:42:07
【问题描述】:

我在循环中遇到 PyMySQL 数据选择问题。

  1. xxx 表包含一条记录 id = 1
  2. 我正在启动脚本

    import pymysql
    import time
    connection = pymysql.connect(host="127.0.0.1",
                                 port=3306,
                                 user="yyy",
                                 passwd="yyy",
                                 db="yyy",
                                 charset='utf8',
                                 cursorclass=pymysql.cursors.DictCursor)
    
    while True:
        with connection.cursor() as cursor:
            sql = "select * from xxx"
            cursor.execute(sql)
            result = cursor.fetchall()
            print result
    
        time.sleep(5)
    
    connection.close()
    
  3. 当我的脚本运行时,我打开 MySQLWorkbench 并将新记录插入 xxx 表等。id = 2

  4. 问题:我的脚本不打印新记录,它只打印 id=1。

如果我重新启动我的脚本,那么它会选择新插入的记录 id=2,但如果我从 MySQLWorkbench 插入另一条记录,它不会找到它(除非我重新启动我的脚本)

你能解释一下如何循环检索数据库中的所有记录吗?

更新:

我通过将autocommit=True 参数添加到连接来解决问题。但是为什么我在选择时需要提交更改?正常吗?

【问题讨论】:

  • 让我们了解一下“事务隔离级别”。

标签: python mysql pymysql


【解决方案1】:

但是为什么我在选择时需要提交更改?正常吗?

是的。这是正常的。您必须学习事务隔离级别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-30
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2014-01-06
    相关资源
    最近更新 更多