Can't seem to insert rows into a MySQL table

Andy Dustman farcepest at gmail.com
Tue Mar 15 18:06:50 EST 2005


Anthra Norell wrote:
> Very true!
> I could verify that cursor.execute () seems to understand  "... %s
...",
> ..."string"... where print () doesn't.. I didn't know that.
> I could also verify that gumfish's ineffective insertion command
works fine
> for me. (Python 2.4, mysql-3.23.38). So it looks like the problem is
with
> MySQL (e.g. table name, column names, ...)

I'm not sure if this is what you are referring to, but here's the
definitive answer:

MySQLdb uses %s as a parameter placeholder. When you pass the
parameters in a tuple as the second argument (as PEP-249 and the API
documentation tells you to), MySQLdb escapes any special characters
that may be present, and adds quotation marks as required.

However, the only parameters you can pass in that way are SQL literal
values, i.e. 15, 'string literal', '2005-03-15', etc. You can NOT pass
in things like names (column, table, database) or other pieces of
arbitrary SQL; these would be treated as strings, and thus be quoted.

Anything other than literal values has to be added some other way,
either by use of format strings and % or string concatenation, or
whatnot. You can double the % (i.e. %%s) so that if you also have
parameters to pass, their placeholder will be preserved.

You need to be very careful about what you allow to be inserted into
your SQL query when not using the quoting/escaping of execute().

> > In <mailman.410.1110836641.1799.python-list at python.org>, Anthra
Norell
> > wrote:
> >
> > > Try to use % instead of a comma (a Python quirk) and quotes
around your
> > > strings (a MySQL quirk):
> > >
> > >    cursor.execute("INSERT INTO edict (kanji, kana, meaning)
VALUES ('%s',
> > > '%s', '%s')" % ("a", "b", "c") )

Don't do this.




More information about the Python-list mailing list