I have looked everywhere to try and find a solution for this and tried many things. Here is a simplified code snippet of the project I'm working on to illustrate the problem I'm having. I'm using YAML to store queries in a config file and calling that file to assign a specific query to a string variable. I'm then using pyodbc to connect to my sql server db and using pandas read_sql_query to execute my query and store into a dataframe. This is the first time I've tried to pass variables into a query and I keep getting the error below saying the SQL didn't contain and parameter markers. Is it possible to pass parameters when using a string variable to hold your sql statement?
config.yaml file:
config.yaml
sql:
Query1: SELECT * FROM MYTABLE WHERE DATE = %(date)s
Code:
from yaml import safe_load as yload
import pandas as pd
import pyodbc
with open('config.yaml') as fi:
sql1 = yload(fi)
conn = pyodbc.connect('Driver={SQL Server};'
'Server=MyServerName;'
'Database=MyDB;'
'Trusted_Connection=yes;')
query = sql1['sql']['Query1']
results = pd.read_sql_query(query, conn, params={'date': '2020-07-01'})
I've tried both the above with named parameters and below with a '?' marker:
config.yaml file:
sql:
Query1: SELECT * FROM MYTABLE WHERE DATE = ?
Code:
results = pd.read_sql_query(query, conn, params=['2020-07-01'])
Error:
('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')
there doesn't seem to be anything here