views:

407

answers:

3

What am I doing wrong here?

 i = 0
 cursor.execute("insert into core_room (order) values (%i)", (int(i))

Error:

 int argument required

The database field is an int(11), but I think the %i is generating the error.

Update:

Here's a more thorough example:

time = datetime.datetime.now()
floor = 0
i = 0

try: booster_cursor.execute('insert into core_room (extern_id, name, order, unit_id, created, updated) values (%s, %s, %s, %s, %s, %s)', (row[0], row[0], i, floor, time, time,)) except Exception, e: print e

Error:

  (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order, unit_id, created, updated) values ('99', '99', '235', '12', '2009-07-24 1' at line 1")
+3  A: 

Two things. First, use %s and not %i. Second, parameters must be in a tuple - so you need (i,) (with comma after i).

Also, ORDER is a keyword, and should be escaped if you're using it as field name.

Pavel Minaev
The %i argument is a int in the db. I need to use %s?
slypete
@slypete: Yes, use `%s`. MySQLdb uses `format` as its default `paramstyle`. PEP 249 for more info: http://www.python.org/dev/peps/pep-0249/
Adam Bernier
If I use %s I get a sql error from the MySQL server.
slypete
So, MySQLdb is only capable of inserting into columns that are varchar? That cannot be!!
slypete
@slypete: "a sql error from the MySQL server". Please update the question with the new code and the actual error message.
S.Lott
`%s` doesn't mean string here, so it's not limited to `VARCHAR`. If you give it an `int`, it will expand to a numeric literal in SQL. For the reason why your query still doesn't work, see the updated answer.
Pavel Minaev
@slypete: the column's datatype has nothing to do with the `%s`. That is just the convention for how arguments are passed to MySQLdb's `execute` method.
Adam Bernier
I think it's order column name, stupid me! Let's see...
slypete
Thanks I had multiple problems. Main one being order used as a column name!
slypete
+1  A: 

I believe the second argument to execute() is expected to be an iterable. IF this is the case you need to change:

(int(i))

to:

(int(i),)

to make it into a tuple.

Mark Roddy
Exactly, this should solve the problem.
Adam Byrtek
A: 

You should be using ? instead of %i probably. And you're missing a parenthesis.

cursor.execute("insert into core_room (order) values (?)", (int(i),))
Evan Fosmark
@Evan: you definitely have the right idea, but this `paramstyle` is known as `qmark`, and AFAIK is not supported by MySQLdb.
Adam Bernier
Ya, I just wrote it quick to demo my bad.
slypete