【问题标题】:Interrupting running queries before closing connection MySQL Python connector在关闭连接 MySQL Python 连接器之前中断正在运行的查询
【发布时间】:2022-01-11 23:00:09
【问题描述】:

我正在通过 Python SQL 连接器运行一系列 SQL 查询,这可能需要很长时间。我正在使用 interruptingcow 包来停止耗时超过 10 秒的查询。然后,当我识别出这种查询时,我会关闭光标和连接,以便尝试正确地杀死它们。

但我怀疑即使连接关闭,这些查询仍在服务器上运行,这会减慢其余查询的运行时间。 是否有解决方案在重新打开连接之前刷新服务器上运行的所有查询。如果可能的话,也许我可以保持连接和光标打开。

这是我正在使用的部分代码:

from interruptingcow import timeout
import mysql.connector

cursor = cnx.cursor()
cursor_open = True

for email in emails:

    if cursor_open is False:
        cnx = mysql.connector.connect(**config)
        cursor = cnx.cursor()

    query = journey_query.format(email=email)
    try:
        with timeout(10, exception=RuntimeError):
            results = cursor.execute(query, multi=True)
            for result in results:
                if result.with_rows:
                    abc = result.fetchall()[0]
                else:
                    continue
    except RuntimeError:
        cursor.close()
        cnx.close()
        cursor_open = False
        continue

cursor.close()
cnx.close()

【问题讨论】:

标签: python mysql-python mysql-connector


【解决方案1】:

根据Killing threads 上的 oracle 文章,这将使连接保持打开状态,但会终止正在运行的查询。

cnx.connection_id 是运行查询的线程 ID。 Documentation

cursor.execute('KILL QUERY %s', (cnx.connection_id,))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2022-01-02
    • 2020-03-31
    • 1970-01-01
    • 2021-02-06
    相关资源
    最近更新 更多