【发布时间】:2017-07-21 21:45:24
【问题描述】:
我使用 python 模块 mysql.connector 连接到 AWS RDS 实例。
现在,我们知道,如果我们有一段时间没有向 SQL Server 发送请求,连接就会断开。
为了处理这个问题,我会重新连接到 SQL,以防读/写请求失败。
现在我的问题是 “请求失败”,失败非常重要。只有这样我才能重新连接并重试我的请求。 (我已将其作为代码 sn-p 中的注释指出)。
对于像我这样的实时应用程序,这是一个问题。我怎么能解决这个问题?是否可以查明断开连接是否已经发生,以便我可以尝试新的连接而无需等待读/写请求?
这是我现在在代码中处理它的方式:
def fetchFromDB(self, vid_id):
fetch_query = "SELECT * FROM <db>"
success = False
attempts = 0
output = []
while not success and attempts < self.MAX_CONN_ATTEMPTS:
try:
if self.cnx == None:
self._connectDB_()
if self.cnx:
cursor = self.cnx.cursor() # MY PROBLEM: This step takes too long to fail in case the connection has expired.
cursor.execute(fetch_query)
output = []
for entry in cursor:
output.append(entry)
cursor.close()
success = True
attempts = attempts + 1
except Exception as ex:
logging.warning("Error")
if self.cnx != None:
try:
self.cnx.close()
except Exception as ex:
pass
finally:
self.cnx = None
return output
在我的应用程序中,从 mysql 读取时,我不能容忍超过 1 秒的延迟。
在配置 mysql 时,我只做以下设置:
SQL.user = '<username>'
SQL.password = '<password>'
SQL.host = '<AWS RDS HOST>'
SQL.port = 3306
SQL.raise_on_warnings = True
SQL.use_pure = True
SQL.database = <database-name>
【问题讨论】:
标签: python mysql mysql-connector mysql-connector-python mysqlconnection