I need to make a function with parameterized values to loop different queries with the same structure, I wrote the following code:
import pandas as pd
cnxn_str = ("Driver={SQL Server Native Client 10.0};"
"Server=xx.xxx.xxx.xx,xx;"
"Database=dbase;"
"UID=sa;"
"PWD=pswd;")
cnxn = pyodbc.connect(cnxn_str)
cursor = cnxn.cursor()
def TRX(tbl_name, var_value):
import pandas as pd
#route by hour----
query = print("SELECT TOP 100 * FROM [DB].[dbo]." tbl_name " WHERE var1 IN ('" var_value "')")
df = pd.read_sql_query(query, cnxn)
return(df)
When I run it, for example:
TRX(tbl_name = '[table1]', var_value = 'a')
It returns the following error:
DatabaseError: Execution failed on sql 'None': The first argument to execute must be a string or unicode query.
Which approach should I use?
CodePudding user response:
I think this should work
query_sql = ''' SELECT COL FROM {} WHERE COL = '{}' '''.format(table_name, col_value)