LINUX.ORG.RU

Python Mysql reconnect

 ,


0

2

Всем привет! Как сделать так, чтобы при таймауте соединения с базой происходило переподключение к ней? Везде рекомендуют ping, но оно не работает. Пока использую вот такой код и он не работает:

while True:  #it works until the data was not saved                                                   
    try:                                                                                              
        self.cur.execute("SELECT property FROM objects WHERE id = %s", str(self.object_id))              
        # Delay of aggregator                                                                         
        self.agg_delay = int(self.cur.fetchall()[0][0])                                               
        break                                                                                         
    except pymysql.err.OperationalError:                                                              
        self.conn.ping(True)

Выдает вот такое:

  File "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py", line 112, in execute
    result = self._query(query)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py", line 230, in _query
    conn.query(q)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 607, in query
    self._affected_rows = self._read_query_result()
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 691, in _read_query_result
    result.read()
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 869, in read
    self.first_packet = self.connection.read_packet()
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 685, in read_packet
    packet = packet_type(self)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 200, in __init__
    self.__recv_packet()
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 206, in __recv_packet
    raise OperationalError(2013, "Lost connection to MySQL server during query")
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "back_server.py", line 62, in prepare
    self.cur.execute("SELECT property FROM objects WHERE id = %s", str(self.object_id))
  File "/usr/local/lib/python3.4/dist-packages/pymysql/cursors.py", line 117, in execute
    self.errorhandler(self, exc, value)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 189, in defaulterrorhandler
    raise errorclass(errorvalue)
pymysql.err.OperationalError: (2013, 'Lost connection to MySQL server during query')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 631, in ping
    self._execute_command(COM_PING, "")
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 716, in _execute_command
    self._send_command(command, sql)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 712, in _send_command
    self.wfile.flush()
  File "/usr/lib/python3.4/socket.py", line 391, in write
    return self._sock.send(b)
BrokenPipeError: [Errno 32] Broken pipe

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 1446, in _execute
    result = self.prepare()
  File "back_server.py", line 67, in prepare
    self.conn.ping(True)
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 634, in ping
    self._connect()
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 677, in _connect
    self._request_authentication()
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 719, in _request_authentication
    self._send_authentication()
  File "/usr/local/lib/python3.4/dist-packages/pymysql/connections.py", line 730, in _send_authentication
    self.user = self.user.encode(self.charset)
AttributeError: 'bytes' object has no attribute 'encode' 1.50ms

★★

Последнее исправление: aido (всего исправлений: 2)

У меня так сделано, правда, на C++. В отдельном потоке создается еще одно подключение, которое периодически делает, допустим, SELECT 1. Если это не удалось, ждем, когда восстановится подключение, а затем клонируем (cloneDatabase) это подключение и переподключаемся (setConnection). http://www.prog.org.ru/topic_29315_0.html

anonymous
()

Для начала обрати внимание, что ты суешь в запрос. У тебя это строка str(self.object_id) а должен быть тюпл (self.object_id, )

Deleted
()
Последнее исправление: moon (всего исправлений: 1)

дл начала получаешь соединение из фабрики, а дальше как фантазия подскажет

anonymous
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.