【问题标题】:mysql.connector doesn't detect outside changes to datamysql.connector 未检测到数据的外部更改
【发布时间】:2019-05-06 13:52:45
【问题描述】:

我有一个脚本正在运行,我想在将数据添加到数据库时对其进行处理。

import mysql.connector
import time

wait_time = 2

mydb = mysql.connector.connect(
  host="localhost",
  user="xxx",
  passwd="yyy",
  database="my_database"
)
mycursor = mydb.cursor()

while True:
    sql = "SELECT * FROM data WHERE processed = 0"
    mycursor.execute(sql)
    records = mycursor.fetchall()
    for i, r in enumerate(records):
        print(r)
    time.sleep(wait_time)

但是,如果通过不同的连接插入一行,则该连接不显示。

即如果我通过第三方应用程序连接到我的数据库,并在

中插入一行

但是,如果我重新启动上述脚本,它就会出现。

有什么想法吗?

【问题讨论】:

  • 试试looking at this。也许你的库正在缓存结果。
  • 这是由于默认的 MySQL 隔离级别 REPEATABLE READ。 This answer 简要解释一下。在您的 while 循环的每次迭代中提交您的连接,以刷新您的查询读取的快照。

标签: python mysql


【解决方案1】:

使用消息队列(例如 RabbitMQ)。获取第三方App使用。消息队列实现具有更好的异步处理信息的 API。即使你只是使用消息队列来存储数据库内容的主键。

交替启用二进制日志记录并使用a replication protocol library 处理事件。

【讨论】:

    【解决方案2】:

    我刚刚遇到了同样的错误。最简单的解决方法是……在循环中定义 mydb 和 mycursor。

    import mysql.connector
    import time
    
    wait_time = 2
    
    
    
    while True:
        mydb = mysql.connector.connect(
        host="localhost",
        user="xxx",
        passwd="yyy",
        database="my_database"
       )
        mycursor = mydb.cursor()
        sql = "SELECT * FROM data WHERE processed = 0"
        mycursor.execute(sql)
        records = mycursor.fetchall()
        for i, r in enumerate(records):
            print(r)
        time.sleep(wait_time)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 2018-01-11
      • 2015-01-15
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      相关资源
      最近更新 更多