I'm using pyodbc to get data from a SQL Server, using the script shown here:
conn = pyodbc.connect('DSN=DATASOURCE')
tbl = "SELECT TableA.Field_1 \
FROM TableA \
WHERE TableA.Date>=2019/04/01"
SQL_Query = pd.read_sql_query(tbl, conn)
conn.close
Now I want to make this query into a Python function, where I can change the date (2019/04/01) in the example above as a function variable.
I found pyodbc offers parameterization, but all in the context of cursor.execute
function.
Ideally, I'd like to create a function like this:
def DB_Query(date):
conn = pyodbc.connect('DSN=DATASOURCE')
tbl = "SELECT TableA.Field_1 \
FROM TableA \
WHERE TableA.Date>=?", date
SQL_Query = pd.read_sql_query(tbl, conn)
conn.close
return SQL_Query
Apparently this doesn't work because tbl
has to be a normal string, but is it possible to use pyodbc's parameterization feature together with pandas' pd.read_sql_query
or pd.read_sql
?