title: Close SQLAlchemy connection
body: <p>I have the following function in python:</p>
  
  <pre><code>def add_odm_object(obj, table_name, primary_key, unique_column):
      db = create_engine('mysql+pymysql://root:@127.0.0.1/mydb')
      metadata = MetaData(db)
      t = Table(table_name, metadata, autoload=True)
      s = t.select(t.c[unique_column] == obj[unique_column])    
      rs = s.execute()
      r = rs.fetchone()
      if not r:
          i = t.insert()
          i_res = i.execute(obj)
          v_id = i_res.inserted_primary_key[0]
          return v_id
      else:
          return r[primary_key]   
  </code></pre>
  
  <p>This function looks if the object <code>obj</code> is in the database, and if it is not found, it saves it to the DB. Now, I have a problem. I call the above function in a loop many times. And after few hundred times, I get an error: <code>user root has exceeded the max_user_connections resource (current value: 30)</code> I tried to search for answers and for example the question: <a href="https://stackoverflow.com/questions/8645250/how-to-close-sqlalchemy-connection-in-mysql">How to close sqlalchemy connection in MySQL</a> recommends creating a <code>conn = db.connect()</code> object where <code>db</code>is the engine and calling <code>conn.close()</code> after my query is completed. </p>
  
  <p>But, where should I open and close the connection in my code? I am not working with the connection directly, but I'm using the <code>Table()</code> and <code>MetaData</code> functions in my code.</p>