gpt4 book ai didi

python - MySQL mysql.connector.cursor 中 weakref 的用途

转载 作者:行者123 更新时间:2023-11-29 02:24:17 24 4
gpt4 key购买 nike

通过使用MySQL官方python驱动程序mysql.connector,以下代码片段可以正常工作。

# -*- coding: utf-8 -*-

import mysql.connector

conn = mysql.connector.connect(...)
cursor = conn.cursor()

cursor.execute(...)

但是当我使用链式调用创建游标时,

# -*- coding: utf-8 -*-

import mysql.connector

cursor = mysql.connector.connect(...).cursor()

cursor.execute(...)

我遇到异常:ReferenceError:弱引用对象不再存在

是由于在mysql.connector.cursor源码中使用了weakref

def _set_connection(self, connection):
"""Set the connection"""
try:
self._connection = weakref.proxy(connection)
self._connection._protocol # pylint: disable=W0212,W0104
except (AttributeError, TypeError):
raise errors.InterfaceError(errno=2048)

weakref不会增加对临时连接对象的引用计数,所以after语句

mysql.connector.connect(...).cursor()

连接对象似乎被垃圾收集回收。

因为在 mysql.connector.connection 源代码中,没有对游标对象的引用。

mysql.connector.cursor 中的 weakref 可能未设置以解决循环引用问题。

有谁知道为什么要设置 weakref 来引用游标的连接?

谢谢。

最佳答案

如果您检查项目的修订历史,the commit that introduces the use of weakref简单地说:

  • Most objects now use weak references: there was no bug or leak which showed we needed to doso however. Can be revereted.

因此,这似乎只是为了避免潜在错误或泄漏的预防性决定,而不是解决特定问题的更改。

关于python - MySQL mysql.connector.cursor 中 weakref 的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25824072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com