简体   繁体   中英

How do I catch _mysql_exceptions.OperationalError: 2002 in python

I'm using a python script to add mosquitto messages to MySQL tables, this is all working fine, I'm catching _mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away') so that the script keeps running if there have been no message for more than 12 hours and I'm catching duplicate time entries which also caused problems.

The problem is that when MySQL server is not running for whatever reason, I want the script to simply not update the database (because it can't) and keep listening for the next message.

So basically, how do I catch;

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

This is the full code I'm using;

#!/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

Thanks for any help.

EDIT:

It looks like the error(s) were coming from elsewhere in the code rather where I was looking. I will update this post again later with details.

I spotted it trying to get sample output to add to this post so posting here did help me.

Your code seems to have a starting example on how to do what you're asking:

except mdb.Error as ee:
...

You have no choice but to catch the exception type and inspect the fields for your desired mysql-specific error codes since the rdbms errors are wrapped inside.

From the official doc MySQLdb User's Guide - MySQL-Python :

There's no return value from this, but exceptions can be raised. The exceptions are defined in a separate module, _mysql_exceptions, but _mysql exports them. Read DB API specification PEP-249 to find out what they are, or you can use the catch-all MySQLError.

It's a good idea (always) to read up the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM