如何在python中捕获_mysql_exceptions.OperationalError:2002

时间:2018-02-18 10:58:15

标签: python mysql mosquitto

我使用python脚本将mosquitto消息添加到MySQL表中,这一切正常,我抓住了_mysql_exceptions.OperationalError :( 2006年,' MySQL服务器已经消失了#39 ;)以便在没有超过12小时的消息的情况下脚本继续运行,并且我捕获重复的时间条目也会导致问题。

问题是当MySQL服务器由于某种原因没有运行时,我希望脚本不会更新数据库(因为它不能)并继续监听下一条消息。

基本上,我怎么抓住;

_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")

这是我正在使用的完整代码;

#!/usr/bin/python

import paho.mqtt.client as mqtt
import time
import MySQLdb as mdb
import sys

con = None

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
    print time.strftime("%Y-%m-%d_%H:%M:%S")
    print("Connected to localhost with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("testing/temp")
    print("Logging testing/temp to MySQL Database")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    dogs = msg.payload, msg.topic.replace("/","_")
    sql = "INSERT INTO %s VALUES(now(), '%s')" % (dogs[1],dogs[0])
    global con
    try:
         cur = con.cursor()
         cur.execute(sql)
    except AttributeError:
         con = mdb.connect('localhost', 'mqttman', 'thepassword', 'mqtt');
         cur = con.cursor()
         cur.execute(sql)
    except mdb.Error as ee:
         print msg.topic, "caught" , ee
         if ee[0] == 2006:
            con = mdb.connect('localhost', 'mqttman', 'thepassword', 'mqtt');
            cur = con.cursor()
            cur.execute(sql)
         if ee[0] == 1062:
            time.sleep(1)
            cur.execute(sql)
         if ee[0] == 2002:
            print "Waaaaa"
            pass
    except mdb.InterfaceError:
        print "errors all around"
    except:
       print "it's really bad"
    con.commit()


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("mqttserver", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.

try:
    client.loop_forever()
except KeyboardInterrupt:
    pass

感谢您的帮助。

编辑:

看起来错误来自代码中的其他地方而不是我正在寻找的地方。稍后我会再次更新此帖子的详细信息。

我发现它试图将示例输出添加到此帖子中,因此在此处发布确实对我有帮助。

1 个答案:

答案 0 :(得分:1)

您的代码似乎有一个关于如何做您要求的开始示例:

except mdb.Error as ee:
...

除了捕获异常类型并检查字段以查找所需的特定于mysql的错误代码之外别无选择,因为rdbms错误被包含在内部。

来自官方文档MySQLdb User's Guide - MySQL-Python

  

此处没有返回值,但可以引发异常。异常在单独的模块_mysql_exceptions中定义,但_mysql导出它们。阅读DB API规范PEP-249以了解它们是什么,或者您可以使用catch-all MySQLError。

阅读文档是一个好主意(总是)。