Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write variable after reading .sql query

When I have to pass a parameter before running a sql query, I usually do

date = '20220101'

query = f'''SELECT * FROM TABLE WHERE DATE = '{date}''''

On an attempt to reduce the lenght of code, I created a query.sql file with the query above but I’m failing to pass the date variable inside my query, before running the sql.

For reading I’m using

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sql_query = open("query.sql", "r")
sql_as_string = sql_query.read()

df = pd.read_sql(sql_as_string, conn)

Is there a way around, instead of pasting the whole SQL query at my .py code?

I’m using pyodbc, ODBC Driver 17 for SQL Server

>Solution :

Use a parametrized query, not string formatting.

The file should just contain the query, with a ? placeholder for the variable.

SELECT * FROM TABLE WHERE DATE = ?

Then you can do

with open("query.sql", "r") as f:
    sql_query = f.read()

df = pd.read_sql(sql_query, conn, params=(date, ))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading