python下保持mysql连接,避免“MySQL server has gone away“方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python下保持mysql连接,避免“MySQL server has gone away“方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2011字,纯文字阅读大概需要3分钟。
内容图文
![python下保持mysql连接,避免“MySQL server has gone away“方法](/upload/InfoBanner/zyjiaocheng/1111/16f7b78547df4fcdb53b9a92754e92b6.jpg)
因需要对saltstack的所有动作进行入库采集,网上采集脚本mysql连接会因超时而断开,导致守护进程在下一次采集数据时提示:
Traceback (most recent call last): File "./salt_event_to_mysql.py", line 39, in <module> ret[‘success‘], json.dumps(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 36, in defaulterrorhandler _mysql_exceptions.OperationalError: (2006, ‘MySQL server has gone away‘)
后退出,解决方法是采用类似mysql_ping()的方法在每次数据入库前做一次检测,唤醒连接,以下是完整代码:
#!/bin/env python #coding=utf8 # Import python libs import json # Import salt modules import salt.config import salt.utils.event # Import third party libs import MySQLdb __opts__ = salt.config.client_config(‘/etc/salt/master‘) # Create MySQL connect 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() # Listen Salt Master Event System event = 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
原文:http://318106.blog.51cto.com/308106/1583891
内容总结
以上是互联网集市为您收集整理的python下保持mysql连接,避免“MySQL server has gone away“方法全部内容,希望文章能够帮你解决python下保持mysql连接,避免“MySQL server has gone away“方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。