0

I have a variable like below in python;

run_id=5654

When i execute the below code;

df=curs.execute("select* from [DATABASE] where RunId=run_id")

I got an error:

DataError: ('22018', "[22018] [Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting the varchar value 'run_id' to data type smallint. (245) (SQLExecDirectW)")

Could you please help me about this? How can i proceed?

Salih
  • 719
  • 1
  • 6
  • 12
  • 1
    You need to learn how to pass a variable to your query as a parameter – Ilyes Nov 01 '19 at 13:40
  • Possible duplicate of [How to use variables in SQL statement in Python?](https://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python) – Buckeye14Guy Nov 01 '19 at 13:42

1 Answers1

1

Assuming you are connecting to your SQL Server instance using pyodbc, you should use a prepared statement with ? as the placeholder:

run_id = '5654'
df = curs.execute("SELECT * FROM [DATABASE] WHERE RunId = ?", (run_id,))
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • yeah you are right, but i got this error: ProgrammingError: ('Invalid parameter type. param-index=0 param-type=numpy.int64', 'HY105') – Salih Nov 01 '19 at 14:04
  • It appears that the `RunId` column is some sort of text. Then you need to bind a string variable, q.v. my updated answer. – Tim Biegeleisen Nov 01 '19 at 14:07