【问题标题】:mysql.connector.connect doesn't seem to have persistent connection through functionsmysql.connector.connect 似乎没有通过函数的持久连接
【发布时间】:2018-09-25 07:51:35
【问题描述】:

在带有 Flask 框架的 python 中使用 mysql 时遇到了一个小问题。我已经设置了一个函数(get_db()),一旦请求连接到数据库,并为稍后请求它的函数提供相同的连接(在同一请求中)。

import mysql.connector #mysql-connector-python==8.0.12

def get_db():
if 'db' not in g:
    try:
        click.echo("Trying to connect")
        cnx = mysql.connector.connect(user='stack', password='overflow',
                          host='127.0.0.1',
                          database=DB_NAME)
        g.db = cnx
        return g.db
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            click.echo("Connection failed! Check username and password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            click.echo("Database does not exist")
        else:
            click.echo("Unknown error: {} ".format(err))
    else:
        cnx.close()
    # Connection to db cannot
    # be established.
    # click.echo("Will exit from database")
    exit(1)

click.echo("Using existing connection")
return g.db

在其他功能中我是这样使用的:

(...)
cnx = get_db()
cursor = cnx.cursor()
(...)

使用数据库的第一个函数工作正常。然后当另一个尝试连接cursor 失败时,因为cnx 没有连接:

raise errors.OperationalError("MySQL Connection not available.")

有没有人有办法解决这个问题?

一种解决方案是为每个函数再次创建连接,但为了性能,我宁愿尽可能重用连接。

【问题讨论】:

    标签: mysql flask mysql-connector-python


    【解决方案1】:

    我目前最终得到的解决方案是在每次方法需要数据库连接时使用reconnect

    我不知道这是否会产生connect() 的开销,但它适用于当前的用例。

    代码将如下所示:

    def get_db():
    if 'db' not in g:
        try:
            cnx = mysql.connector.connect(user='tom', password='jerry',
                              host='127.0.0.1',
                              database=DB_NAME)
            g.db = cnx
            click.echo("Returns new connection")
            return g.db
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                click.echo("Connection failed! Check username and password")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                click.echo("Database does not exist")
            else:
                click.echo("Unknown error: {} ".format(err))
    
    cnx = g.db
    cnx.reconnect() <--- Doing a reconnect each time
    return cnx
    

    【讨论】:

      【解决方案2】:

      您可以使用池:https://dev.mysql.com/doc/connector-python/en/connector-python-connection-pooling.html

      导入 mysql.connector

      conf = {"user":"username", "password":"*****", host="hostname"}
      pool_cnc = mysql.connector.connect(pool_name="my_pool", **conf)
      
      # Take one connection using the name of the pool:
      cnc1 = mysql.connector.connect(pool_name = pool_cnc.pool_name)
      cnc1.is_connected()
      
      # Should output True
      

      在给定的链接上还有一个关于显式池连接的示例

      【讨论】:

        猜你喜欢
        • 2011-03-12
        • 2015-08-26
        • 2013-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-24
        • 1970-01-01
        相关资源
        最近更新 更多