Hello,
Iam using the pyodbc module to read / write to the .mdb file.i have written the following code for extracting some data from db and it works fine.

cursor.execute("select company_name, param_key,com_value \
                from key_financial_ratio \
                where param_key = ? \
                and com_value > ? \
                and com_value < ?" \
                ,[paramKey,startValue,endValue])

I wish to change the above to

sql_key = "select company_name, param_key,com_value \
                from key_financial_ratio \
                where param_key = ? \
                and com_value > ? \
                and com_value < ?" \
                ,[paramKey,startValue,endValue]
cursor.execute(sql_key)

But it is not accepting and throwing the below error.
"The first argument to execute must be a string or unicode query."

How to solve this?

Print sql_key and that should provide some insight. You are creating a string, and not querying an SQL database, so string formatting is required. The following assumes that all fields are strings and not integers or floats.

sql_key = "select company_name, param_key,com_value from key_financial_ratio                 where param_key = %s and com_value > %s and com_value < %s" % (paramKey,startValue,endValue)
print sql_key

This is somewhat dependent on which flavor of SQL you are using, and which version of Python you have installed, so once again print the string, and see if it is what you expect. Note that the string can, and probably should be divided into multiple, shorter segments for easier reading. If this doesn't work as expected, post back with some samples.

Edited 5 Years Ago by woooee: n/a

This article has been dead for over six months. Start a new discussion instead.