首页 > 解决方案 > 使用 pandas.read_sql 重用数据库连接对象以进行高频更新 [Python/MariaDB/alive-db-connection]

问题描述

我正在尝试重用 MariaDB 的数据库连接对象,并将其存储为 Singleton 类的静态变量。

...import mariadb

class SingletonAux:
    __connection_string = None

    @staticmethod
    def get_connection_string():
        if not SingletonAux.__connection_string:   #<-- This part of the code never evaluates to false
            SingletonAux.__connection_string = mariadb.connect(
                user=f"{ENV-Variable}",
                password=f"{ENV-Variable}",
                host=f"{ENV-Variable}",
                database=f"{ENV-Variable}")
        return SingletonAux.__connection_string

    def __init__(self):

        if SingletonAux.__connection_string:
            print("Singleton cannot be instantiated more than once")
        else:
            self.get_connection_string()
            SingletonAux.__connection_string = self

...

然后,在下面我调用调用类的连接:

...
pd.read_sql(compound_sql, con=con.get_connection_string(), etc-etc

但是每次执行上面的'read_sql'时,都会创建新的类对象,并且connection_string总是None,根本不是单例。我究竟做错了什么?

如果有人要问为什么,我会尝试以高频率(每秒 3-4 次调用)从我的 MariaDB 数据库中查询数据。MariaDB 连接字符串初始化大约需要 0.4 秒。如果我将 SingletonAux 类视为 mariaDB 连接字符串,例如:

pd.read_sql(compound_sql, con=SingletonAux, etc-etc

然后 Pandas 抱怨说 SingletonAux 没有游标功能,这是真的。如果我需要以某种方式取消引用 maria 对象,但我不知道如何。

如果我的基本代码中有错误,请帮助。

标签: pythonpandasmariadbread-sql

解决方案


推荐阅读