【发布时间】: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