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?
+ "')"). When in doubt, write your sql to a variable and do aprintto see what the SQL looks like and try to execute in a client like SSMS. It's easier to debug when you can see what's being submitted. It's also worth noting that since you are concatenating together your sql you are open to a sql injection attack.pd.read_sql_query()is referencing variablesql_etapasbut your sql is in variablequery. Perhaps that just a typo when you ported your code to stackoverflow?var_valueusing parameterized query (whatever your library/module for sql server connection syntax is).sometable;DROP TABLE sometable--which, if permissions allow it in your database, would cause yoursometableto disappear off the face of the earth.