Celery and SQLAlchemy - This result object does not return rows. It has been closed automatically Celery and SQLAlchemy - This result object does not return rows. It has been closed automatically multithreading multithreading

Celery and SQLAlchemy - This result object does not return rows. It has been closed automatically


All together: any advise to skip these difficulties?

yes. you absolutely cannot use a Session (or any objects which are associated with that Session), or a Connection, in more than one thread simultaneously, especially with MySQL-Python whose DBAPI connections are very thread-unsafe*. You must organize your application such that each thread deals with it's own, dedicated MySQL-Python connection (and therefore SQLAlchemy Connection/ Session / objects associated with that Session) with no leakage to any other thread.

  • Edit: alternatively, you can make use of mutexes to limit access to the Session/Connection/DBAPI connection to just one of those threads at a time, though this is less common because the high degree of locking needed tends to defeat the purpose of using multiple threads in the first place.


I got the same error while making a query to SQL-Server prodcedure using SQLAlchemy.In my case, adding SET NOCOUNT ON to the stored procedure fixed the problem.

ALTER PROCEDURE your_procedure_nameASBEGIN    -- SET NOCOUNT ON added to prevent extra result sets from    -- interfering with SELECT statements.    SET NOCOUNT ON;    -- Insert statements for your procedure here    SELECT *    FROM your_table_name;END;

Check out this article for more details


This error occurred for me when I used a variable in Python
and parsed it with an UPDATEstatement using pandas pd.read_sql()

Solution:

I simply used mycursor.execute() instead of pd.read_sql()

import mysql.connector and from sqlalchemy import create_engine

Before:

pd.read_sql("UPDATE table SET column = 1 WHERE column = '%s'" % variable, dbConnection)

After:

mycursor.execute("UPDATE table SET column = 1 WHERE column = '%s'" % variable)

Full code:

import mysql.connectorfrom sqlalchemy import create_engineimport pandas as pd# Database Connection Setup >sqlEngine = create_engine('mysql+pymysql://root:root@localhost/db name')dbConnection = sqlEngine.connect()db = mysql.connector.connect(    host="localhost",    user="root",    passwd="root",    database="db name")mycursor = db.cursor()variable = "Alex"mycursor.execute("UPDATE table SET column = 1 WHERE column = '%s'" % variable)