0

Here's my Python code:

import pandas as pd
import psycopg2

# connect to db
conn = psycopg2.connect(
    host="localhost",
    database="postgres",
    user="postgres",
    port= "5432",
    password="example")

# read in the sql file
fd = open('SQL/example.sql', 'r')
sqlFile = fd.read()
fd.close()

# get query
mydate = '1/1/2021'
data = pd.read_sql(sqlFile, conn)

Here's my SQL script:

select *
from myschema.table
where date = $mydate

I want to pass my Python variable "mydate" to SQL. So when I run SQL, it would show the date stored in the variable as such. i.e. The string sqlFile would actually show:

select *
from myschema.table
where date = '1/1/2021'

How can I do this?

ssmm
  • 149
  • 2
  • 15
  • Does this answer your question? [Pandas read\_sql with parameters](https://stackoverflow.com/questions/24408557/pandas-read-sql-with-parameters) – costaparas Jan 24 '21 at 03:52
  • Do `data = pd.read_sql(sqlFile, conn, params={"mydate": mydate})`, and change your files to use format: i.e. `where date = %(mydate)s` – costaparas Jan 24 '21 at 03:52

0 Answers0