即使在执行程序后,连接在 Postgresql 数据库上仍处于活动状态

时间:2020-12-30 09:42:48

标签: python postgresql sqlalchemy flask-sqlalchemy

当我运行读取 PostGresql 数据库的 python 代码以从表中读取配置时。我正在使用 sqlalchemy engine.connect 建立连接。我正在使用 conn.close() 命令关闭连接。但我的数据库仍然显示活动的数据库连接。

def get_postgres_data_df(self, table_name):
    global read_conn
    result_df = pd.DataFrame()
    if self.debug:
        print('Inside PostgreSQLOperations Class get_postgres_data_df method')

    connection_string = 'postgresql://' + \
                        self.user + ':' + \
                        self.password + '@' + \
                        self.host + ':' + \
                        self.port + '/' + \
                        self.database
    try:
        if self.debug:
            print('Trying to read from table {0}'.format(table_name))
        engine = sqlalchemy.create_engine(connection_string)

        read_conn = engine.connect()
        print('Connected to database @ ' + self.database)

        if self.debug:
            print(engine.table_names())

    except Exception as e:
        print('Failed to establish the connection', e)
        read_conn.close()
    query = ('SELECT * FROM ' + table_name)

    try:
        result_df = pd.read_sql(sql=query, con=read_conn)
        if self.debug:
            print('Read success for table # ', table_name)
            print(result_df)
        read_conn.close()
    except Exception as e:
        print('Read failed # ', e)
        read_conn.close()
    return result_df

0 个答案:

没有答案