Does pandas need to close connection?

16,362

Solution 1

Looking at the source code, I can't find a con.close() method on any SQL connection object, only the cursor objects for the queries.

I'd close for safe-measure. Whether you do that using with or not is up to you.

Solution 2

For anyone who finds this question and wonders how to close the connection in this example, the following method worked for me: engine.dispose()

Share:
16,362
deez
Author by

deez

Updated on June 04, 2022

Comments

  • deez
    deez almost 2 years

    When using pandas "read_sql_query", do I need to close the connection? Or should I use a "with" statement? Or can I just use the following and be good?

    from sqlalchemy import create_engine
    import pandas as pd
    
    sql = """
        SELECT * FROM Table_Name;
        """
    engine = create_engine('blah')
    
    df = pd.read_sql_query(sql, engine)
    
    print df.head()
    
  • juanpa.arrivillaga
    juanpa.arrivillaga about 7 years
    Yeah, to me is wouldn't make sense to close the connection if it is taking the connection as an argument.
  • OneCricketeer
    OneCricketeer about 7 years
    Right, because it would need to re-open for subsequent queries.
  • hoyland
    hoyland about 7 years
    Connections should generally close when they go out of scope. That said, it's better to close connections when appropriate.
  • chjortlund
    chjortlund over 3 years
    For good measure, here is the reference to official SQLAlchemy documentation with additional explanation: docs.sqlalchemy.org/en/13/core/connections.html#engine-dispo‌​sal