2

I want to pass list values along with other parameter values. following is my scenario. I want to pass multiple values for column "Code" and want to pass single value to "Continent" column.

param = [('AFG', 'IND'),'Asia']
query = "select * from country where Code in (%s) AND Continent = %s"
cursor.execute(query,param)

while executing in Python, I am getting following error.

Failed to execute Query: Failed processing format-parameters; Python 'tuple' cannot be converted to a MySQL type

1
  • It is strange, i put your code in mariadb and it give a total different error: (1241, 'Operand should contain 1 column(s)') Commented Dec 11, 2019 at 11:42

2 Answers 2

2

The trick here is the WHERE IN clause, which isn't really amenable to being parameterized. One option generates an IN clause with the exact number of placeholders in your list:

codes = ('AFG', 'IND')
continent = 'Asia'
params = codes + (continent,)
where_in = ','.join(['%s'] * len(codes))
sql = "SELECT * FROM country WHERE Code IN (%s) AND Continent = %s" % (where_in, '%s')
cursor.execute(sql, params)

To see what the above script actually did, lets look at the various parts:

print(where_in)
print(sql)

%s,%s
SELECT * FROM country WHERE Code IN (%s,%s) AND Continent = %s

The trick here is that we actually use a %s placeholder twice, once for the Python string, and a second time for the SQL query string. Also, we bind a single level tuple containing all bound values:

('AFG', 'IND', 'ASIA')
Sign up to request clarification or add additional context in comments.

4 Comments

@MaxMuster I think you meant to drop this comment under the OP. I have given a correct answer assuming the OP's query be correct.
sorry I see now his query had it also.
Thanks @TimBiegeleisen, I have a question. If I have more than one column has list values, how to pass them? I mean If I want to pass Code and Continent as list values, how to pass them.
Then going by answer you would need two where_in variables, one for each WHERE IN clause, and you would have to substitute and then bind both of them. I won't update my answer, but if you still have doubts feel free to open a new question.
0

first you split the list and then you split the tuple.

param = [('AFG', 'IND'),'Asia']
p1,p2=param[0]
query = "select * from country where Code in ('%s','%s') AND Continent = %s" % (p1,p2,param[1])
cursor.execute(query)

1 Comment

This is incorrect, and the %s placeholders should not be in single quotes (which partially defeats the purpose of using a statement). Also, you are hardcoding WHERE IN plus two items, when in fact future readers of this question might want a solution for an arbitrary number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.