Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Connector/Python stored procedure insert not committing

I'm writing a python script to monitor a few 1wire sensors off of a Raspberry Pi and store the results in a MySQL database. Using the MySQL Connector/Python library I can successfully connect to the database, and run the query however the transaction doesn't seem to fully commit. I know the query runs successfully since the out param is set to the new auto-incremented ID.

CREATE TABLE `lamp`.`sensors` (
 `SensorID` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `SensorSerial` char(15) NOT NULL,
 `SensorFamily` tinyint(4) NOT NULL,
 PRIMARY KEY (`SensorID`),
 UNIQUE KEY `SensorID_UNIQUE` (`SensorID`),
 UNIQUE KEY `SensorSerial_UNIQUE` (`SensorSerial`)
)

CREATE PROCEDURE `lamp`.`AddSensor` (sensorSerial char(15),
                         sensorFamily tinyint, out returnValue int)
BEGIN
 INSERT INTO sensors (SensorSerial,SensorFamily) VALUES (sensorSerial,sensorFamily);
 SET returnValue=LAST_INSERT_ID();
END

However when I attempt to query the table (Select * from sensors) I get 0 results. If I run the procedure from the MySQL Workbench or from a .Net application everything works as expected. Which means I'm missing something when it comes to the Connector/Python, but I have no clue what. I'm extremely baffled since the auto-increment value does increase but no records are added. There are also no errors reported

 def Test(self):
    #this line works fine
    #self.RunProcedure("INSERT INTO sensors (SensorSerial,SensorFamily) VALUES ('{0}',{1})".format(self.ID,self.Family),False,())
    #this line does not?
    args=self.RunProcedure('AddSensor',True,(self.ID,self.Family,-1))
    if args[2]>=1:
        logging.debug("Successfully added sensor data '{1}' for sensor '{0}' to the database".format(self.ID,value))
        return True
    else:
        logging.critical("Failed to add Data to Database for unknown reason. SensorID: {0} Type: {1} Data:{2}".format(self.ID,self.Family,value))

def RunProcedure(self,proc,isStored,args):
    try:
        logging.debug("Attempting to connect to database.")
        connection=mysql.connector.connect(user='root',password='1q2w3e4r',host='localhost',database='LAMP')
    except mysql.connector.Error as e:
        logging.exception("Failed to connect to mysql database.\r\n {0}".format(e))
    else:
        logging.debug("Successfully connected to database.")
        try:
            cursor=connection.cursor()
            if isStored:
                args = cursor.callproc(proc,args)
                return args
            else:
                cursor.execute(proc,args)
            #these do not seem to solve the issue.
            #cursor.execute("Commit;")
            #connection.commit()
        except mysql.connector.Error as e:
            logging.exception("Exception while running the command '{0}' with the args of '{1}' exception is {2}".format(proc,args,e))
        finally:
            logging.debug("Closing connection to database")
            cursor.close()
            connection.close()

Output from to the log looks like this;

2013-06-09 13:21:25,662 Attempting to connect to database.
2013-06-09 13:21:25,704 Successfully connected to database.
2013-06-09 13:21:25,720 Closing connection to database
2013-06-09 13:21:25,723 Successfully added sensor data '22.25' for sensor '10.85FDA8020800' to the database

**Edit

Not sure why but adding autocommit=True to the connection.open params seems to have resolved the issue. Since it was a problem with committing why didn't connection.commit() or the cursor.execute('commit;') correct the issue?

like image 787
Tangeleno Avatar asked Feb 17 '23 07:02

Tangeleno


1 Answers

The problem is actually in your code:

    ..
    try:
        cursor=connection.cursor()
        if isStored:
            args = cursor.callproc(proc,args)
            return args
        else:
            cursor.execute(proc,args)
        connection.commit()
    except mysql.connector.Error as e:
    ..

If you are using the Stored Routine, you are immediately returning, so commit() will never be called.

like image 173
geertjanvdk Avatar answered Mar 12 '23 13:03

geertjanvdk