2

I have code like this:

conn = pyodbc.connect(<Connection Details>)
c = conn.cursor()

employee_id=(100,101)
query = "select * from employees where employeeid in ?"

c.execute(query,employee_id)

I am getting this error:

'The SQL contains 1 parameter markers, but 2 parameters were supplied', 'HY000'

Is there any way to pass this parameter? I don't want to create a dynamic array by concatenation.

Is there any way to name the parameter marker inside the query in case of several where conditions?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Aditya
  • 113
  • 1
  • 7
  • each `?` correlates to 1 parameter. You've passed 2 parameters. What do you expect to occur? If you want to do more than 1 query you should run something like `executemany`, or run `executre` more than 1 time – M Z Jan 11 '21 at 06:47
  • Check the accepted answer from here: https://stackoverflow.com/questions/4574609/executing-select-where-in-using-mysqldb – Som-1 Jan 11 '21 at 06:57
  • @Som-1 you're right, I misread the code which is why I deleted my comment – M Z Jan 11 '21 at 07:02
  • @MZ.there may be several employeeids. so we cant predetermine the number of '?' – Aditya Jan 11 '21 at 07:54

1 Answers1

1

If I remember correctly, the placeholder is %s and not ?.

Regardless, you can use the format method / string formatting to get the job done:

conn = pyodbc.connect(<Connection Details>)
c = conn.cursor()
employee_id=(100,101)

query = "select * from employees where employee_id in {}"
c.execute(query.format(employee_id))
OneCoolBoi
  • 86
  • 5
  • 1
    It's not a secure way to do that. SQL injection is possible with this code. – Som-1 Jan 11 '21 at 06:57
  • To add to what @Som-1 has said, prepared statements exist for a reason – M Z Jan 11 '21 at 06:57
  • 1
    @som-1 I understand it is not a secure way. I just wanted to know how it is done in case I want to do it. :) – Aditya Jan 11 '21 at 07:52
  • @Aditya check my comment under the question - there is a link to similar question, where similar but more secure code provided: https://stackoverflow.com/questions/4574609/executing-select-where-in-using-mysqldb – Som-1 Jan 11 '21 at 11:47