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()
It does close the cursor, but it usually is not necessary because the same happens automatically when csr goes out of scope (and that is usually soon enough). Use it only if you want to remove csr from the namespace and/or reduce references to the object by one.
If you pass it an open file it will keep it open (reading from the current position), if you pass a string then read_csv will open and close the file. In python if you open a file but forget to close it, python will close it for you at the end of the function block (during garbage collection).
read_sql. Read SQL query or database table into a DataFrame. This function is a convenience wrapper around read_sql_table and read_sql_query (for backward compatibility).
To disconnect Database connection, use close() method. If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB.
For anyone who finds this question and wonders how to close the connection in this example, the following method worked for me: engine.dispose()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With