You should add it inside the if block, and pass the connection object to pd.read_sql instead of the engine.
Here's the corrected code:
inspector = inspect(engine)
full_table_name = schema_name + "." + table_name_prefix + "commit"
table_name = table_name_prefix + "commit"
old_commits = pd.DataFrame() # Initialize it to an empty DataFrame by default
# Check if the table exists. Remember to use the 'schema' argument if your DB requires it.
if table_name in inspector.get_table_names(schema=schema_name):
# If the table exists, establish a connection to read data
with engine.connect() as connection:
# Pass the 'connection' object to pd.read_sql
old_commits = pd.read_sql(sql=f"SELECT * FROM {full_table_name}", con=connection)
# else: (no need for an else block as old_commits is initialized to empty DataFrame)
# old_commits = pd.DataFrame()
print(old_commits)
Explanation of the change:
old_commits = pd.DataFrame() outside if/else: It's good practice to initialize old_commits to an empty DataFrame at the start. This ensures that old_commits is always defined, regardless of whether the if block is entered.
with engine.connect() as connection:: This block now wraps the pd.read_sql call. This is the correct way to explicitly open a connection, use it for your operation, and ensure it's automatically closed and returned to the connection pool (even if an error occurs).
con=connection: Inside the with block, you now pass the specific connection object you just opened to pd.read_sql.
While pd.read_sql can take an engine directly (and it will implicitly get and release a connection), using with engine.connect() as connection: gives you more explicit control over the connection lifecycle, which is beneficial if you were to perform multiple operations within a single transaction, or if you just prefer to manage the connection explicitly. For a single read operation, both approaches would functionally work, but your desire to use with engine.connect() is a valid and often preferred pattern.