3

I can't get ? instead of %s to work on an insert with python mysqldb.

I try

cur.execute("""INSERT INTO project (project) VALUES (?) """, ('ham'))

but I get

query = query % db.literal(args)
TypeError: not all arguments converted during string formatting

works fine if I simply substitute ? with %s

What am I doing wrong?

1
  • It uses string formatting operator %s. Use that only Commented Jan 22, 2014 at 11:34

1 Answer 1

6

You can't. The mysqldb adapter only supports the format and pyformat parameter styles.

The Python DB API 2.0 specification supports 5 different paramstyle parameter styles but it is up to the exact database adapter implementation what they support. The mysqldb project documentation tells you what styles are supported by that adapter, and qmark is not one of them.

If you are trying to write SQL suitable for multiple database adapters, you'll most likely have to deal with more issues than just the parameter style. Consider using SQLAlchemy instead, which can generate SQL for you that is more database agnostic (up to a point).

19
  • 1
    The %s parameter style will sanitize the input just like the ? in the call - provided, of course, that you pass your SQL parameters as parameters to the execute method: do not pre-format the string with the %s with the % operator before making the method call.
    – jsbueno
    Commented Jan 22, 2014 at 11:46
  • 1
    @user1170304: Then why not just use %s? Those are SQL parameters. Don't be fooled by the fact that the syntax is the same as string interpolation in Python; it's not the same functionality here. Commented Jan 22, 2014 at 12:51
  • 2
    @user1170304: Use them as SQL parameters; cur.execute("""INSERT INTO project (project) VALUES (%s) """, ('ham',)) will work just fine. Commented Jan 22, 2014 at 12:52
  • 1
    @user1170304: Note that that doesn't use execute(sql % values); it uses execute(sql, values). Commented Jan 22, 2014 at 12:53
  • 1
    @user1170304: That is what SQL parameters do, they sanitize the input and quote it correctly. MySQLdb uses SQL parameters in exactly that fashion, provided you use them correctly. Commented Jan 22, 2014 at 12:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.