title: Sqlalchemy - Error closing cursor Traceback with InternalError : Unread result found
body: <p>I am using sqlalchemy to save data to a mysql database in rds (aurora-serverless).This is being done with a lambda function.</p>
  
  <p>Everything is working fine except the fact that whenever a new lamdba container is initialized, I get the following error. After which everything runs smoothly again unless a new container is created. From whatever I understand, somehow the unread result from the cursor in the old container retains itself and when it tries to one a new container at the initialisation step it tries to somehow close an old cursor and then it throws this exception.</p>
  
  <p>I am creating the engine and the sessionmaker on the global level of my lambda and creating a session and destroying it one each call to my handler.</p>
  
  <pre><code>[ERROR] 2019-08-28T13:37:22.454Z    Error closing cursor
  Traceback (most recent call last):
  File "/var/task/sqlalchemy/engine/base.py", line 1338, in _safe_close_cursor
  cursor.close()
  File "/var/task/mysql/connector/cursor_cext.py", line 402, in close
  self._cnx.handle_unread_result()
  File "/var/task/mysql/connector/connection_cext.py", line 695, in handle_unread_result
  raise errors.InternalError("Unread result found")
  mysql.connector.errors.InternalError: Unread result found
  </code></pre>
  
  <p>Any help in this regard would be really helpful.</p>
  
  <p>Following is a code snippet to help understand the lambda within which this error is thrown</p>
  
  <pre><code>def connect_db():
      def connect():
          return mysql.connector.connect(host=hostname, user=username, password=password, database=database, port=port)
  
      db = create_engine(f'mysql+mysqlconnector://', creator=connect, isolation_level='SERIALIZABLE', echo=False)
      return db
  
  
  # establish connection once per container
  engine = connect_db()
  Data.__table__.create(bind=engine, checkfirst=True)
  Session = sessionmaker(bind=engine)
  
  def save_to_database(data):
      session = Session()
      try:
          ids = [result[0] for result in session.query(Data.id).all()]
          ...
          #saving logic
          ...
          session.bulk_insert_mappings(Data, insert_data)
          session.flush()
  
          session.bulk_update_mappings(Data, update_data)
          session.flush()
  
          session.commit()
  
      except:
          session.rollback()
          raise
      finally:
          session.close()
  
  def handler(event, context):
      output = save_to_database(event)
      return {'records': output}
  </code></pre>