[Tutor] escape-quoting strings
Lloyd Kvam
pythonTutor at venix.com
Mon Nov 1 04:34:34 CET 2004
On Sun, 2004-10-31 at 18:06, Marilyn Davis wrote:
> I got it!!
>
> This works:
>
> ad0 = address.replace('\\', '\\\\')
> ad0 = ad0.replace('\"','\\"')
> db_style0 = '''%%%s%%''' % ad0
> print "0:", db_style0
>
> On Sun, 31 Oct 2004, Rick Pasotto wrote:
>
> > On Sun, Oct 31, 2004 at 01:53:42PM -0800, Marilyn Davis wrote:
> > > Hi Python Tutors,
> > >
> > > I'm having a devil of a time quoting strings properly for MySql.
> >
> > You example did not include any MySql statements. How are you sending
> > the string to MySql?
>
> I didn't want to complicate my question with MySql stuff.
>
> Here is a successful call that depended on the quoting scheme above:
>
> insert ignore into doorman (in_id, msg_id, out_address, status, start) values (60, "1COOZD-0003KN-2z", "\"Toys \\\"R\\\" Us Gift Card Giveaway\" <fqgdmvfjfyvjd at dlawczhyh.montebic.com>", "NO_MESSAGE", "0")
Your real MySQL code was omitted. I'll assume a cursor named curs.
curs.execute(sql_cmd, parameters)
is the general format for executing an SQL statement. With MySQL the
parameter positions are marked with %s - so it looks like string
interpolation. Parameters is a tuple of variables that need to be
inserted into the sql_cmd at the positions marked by %s. DO NOT USE
PYTHON string interpolation. Let the MySQLdb module do it.
For your situation:
sql_cmd = '''insert ignore into doorman (in_id, msg_id, out_address,
status, start) values (60, "1COOZD-0003KN-2z", %s, "NO_MESSAGE", "0")'''
parameters = (address, )
There is no need to change the incoming string value to be able to feed
it into the database.
The Python DBI documentation does not discuss this clearly enough. I
made the same mistake in some of my first DBI programs.
>
>
>
> Thank you.
>
> Marilyn
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp
More information about the Tutor
mailing list