Skip to content

Instantly share code, notes, and snippets.

@renatocfrancisco
Last active July 19, 2023 15:51
Show Gist options
  • Save renatocfrancisco/902cd53890063d0bdaff40481a2bd702 to your computer and use it in GitHub Desktop.
Save renatocfrancisco/902cd53890063d0bdaff40481a2bd702 to your computer and use it in GitHub Desktop.
Query statement in python

The _metadata attribute of the Pandas DataFrame was removed in version 1.3.0, which is why you are receiving a "list indices must be integers or slices, not str" error. The approach I suggested in my previous response would only work for Pandas versions earlier than 1.3.0.

In newer versions of Pandas, you can still access the compiled SQL statement by using the query attribute of the sqlalchemy.engine.ResultProxy object that is returned by pandas.read_sql_query. Here's an example:

import pandas as pd
from sqlalchemy import create_engine

# create a SQLAlchemy engine
engine = create_engine('postgresql://user:password@host:port/database')

# execute a query using pandas
df = pd.read_sql_query('SELECT * FROM mytable WHERE mycolumn = 1', engine)

# get the SQL query string from the result proxy
query_string = str(df._query)

print(query_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment