Keep MySQL connected under Python and avoid the "MySQL server has gone away" method

Source: Internet
Author: User

Due to the need to saltstack all the action of the Storage collection, online collection script MySQL connection will be disconnected due to timeout, causing the daemon to be prompted during the next data acquisition:

Traceback (most recent call last): File "./salt_event_to_mysql.py", line-up, in <module> ret[' success '], Json.du MPs (ret))) file "build/bdist.linux-x86_64/egg/mysqldb/cursors.py", line 173, in execute file "build/bdist.linux-x86_64 /egg/mysqldb/connections.py ", line-defaulterrorhandler_mysql_exceptions, in. Operationalerror: (2006, ' MySQL server has gone away ')

After exit, the workaround is to use a similar mysql_ping () method to do a detection before each data storage, wake up the connection, the following is the complete code:


#!/bin/env python#coding=utf8# import python libsimport json# import salt  modulesimport salt.configimport salt.utils.event# Import third party  Libsimport mysqldb__opts__ = salt.config.client_config ('/etc/salt/master ') # Create  Mysql connectconn = mysqldb.connect (host=__opts__[' MySQL ' [' Host '], user=__opts__[' MySQL ') [' User '], passwd=__opts__[' mysql ' [' Pass '], db=__opts__[' MySQL '] [' db '], port=__opts__[' MySQL '] [ ' Port ']) cursor = conn.cursor () # listen salt master event systemevent =  salt.utils.event.masterevent (__opts__[' Sock_dir ') for eachevent in event.iter_events (full =true):     ### #保持连接的部分 ###########    if conn is none:         conn = mysqldb.connect (host=__opts__[' MySQL ' [' Host ') ], user=__opts__[' MySQL '] [' User '], passwd=__opts__[' mysql ' [' Pass '], db=__opts__[' MySQL '] [' db '], port=__opts__[' MySQL '] [ ' Port '])         cursor = conn.cursor ()      else:        conn.ping (True)     ############ ###############                     ret = eachevent[' data ']    if  "salt/job/"  in eachevent[' tag ']:        # return event         if ret.has_key (' id ')  and ret.has_key (' return '):             # Igonre saltutil.find_job  event            if ret[' fun '] ==  ' Saltutil.find_job":                 continue             if ret[' fun '] ==  ' Test.ping ":                 continue            sql =  ' INSERT  INTO  ' Salt_returns '                   (' fun ',  ' Jid ',  ' return ',  ' id ',  ' success ',  ' Full_ret '  )                  VALUES  (%s,  %s, %s, %s, %s, %s) "             cursor.execute (sql,  (ret[' fun '], ret[' Jid '],                                   json.dumps (ret[' return '),  ret[' id '],                                   ret[' Success '], json.dumps (ret)))              cursor.execute ("COMMIT")     # other event     else:        pass



Keep MySQL connected under Python and avoid the "MySQL server has gone away" method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.