3

I am using Django cursor.execuremany for a while now and I wanted to do some cleading up.

On this Stackoverflow page I read that it is a bad idea to use the string formatting operator, and use a questionmark. How to use variables in SQL statement in Python?

However when I use this in my program I get an error:

TypeError: not all arguments converted during string formatting

This is the code I wrote:

from django.db import connection

values = ((1, "john"), (2, "robert"), (3, "angela"))

cursor = connection.cursor()
query = "REPLACE INTO names (id, name) VALUES (?, ?)"
cursor.executemany(query, values)

When I only replace the ? with %s it works as expected.

Another thing (that got me started searching) is that PyCharm is giving me an error when using %s.

<expression> expedted, got %

This is not the main issue, but I'm not sure if this could make a difference.

What I am using

  • Python 2.7
  • Django 1.4
  • MySql
Community
  • 1
  • 1
Johan Vergeer
  • 5,208
  • 10
  • 48
  • 105

1 Answers1

3

When I only replace the ? with %s it works as expected.

The ? placeholder is used for SQLite only:

Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute() method. (Other database modules may use a different placeholder, such as %s or :1.)

MySQL drivers expect to see %s as a query parameter placeholder:

query = "REPLACE INTO names (id, name) VALUES (%s, %s)"
cursor.executemany(query, values)

Another thing (that got me started searching) is that PyCharm is giving me an error when using %s.

PyCharm does not issue any warnings on my end. You've probably did something different:

enter image description here

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195