Trying to load a SQL Server database table into a Python pandas DataFrame dynamically based on production date of the reports. My issue is the following, when I write:
import pyodbc
conn = pyodbc.connect(server = "10.87.254.73", Database= "CTData", Driver ="{SQL Server}")
PCBondsDB = pd.read_sql_query("Select * From [MarketData].[pcbond].[PCbonds] where ClosingDate = '2020-04-13'", conn)
conn.close()
It works, I can connect to the Database and extract my table, but if I change the where ClosingDate= to a variable containing the date as a string it won't work.
Suppose DateProd = '2020-04-13' and now I try:
PCBondsDB = pd.read_sql_query("Select * From [MarketData].[pcbond].[PCbonds] where ClosingDate =
'DateProd'",
It throws me an error saying: Execution failed on sql 'Select * From [MarketData].[pcbond].[PCbonds] where ClosingDate = 'DateProd'': ('22007', '[22007] [Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting date and/or time from character string. (241) (SQLExecDirectW)')
Which makes absolutely no sense as to why when I pass it as a litteral where ClosingDate= '2020-04-13' it works, but when I try to use a variable where ClosingDate = 'DateProd' (which contains the exact same value and datatype being a string) it won't work and throws an error.
I tried doubling, tripling the quotes, inversing single and double quotes, nothing seems to work. I looked around the forum and couldn't find an answer to this specific problem. I think the solution is easy but I am a rather novice in Python and would like to know.. I am trying to make this dynamic, so yes I need to use a variable...
Thanks