[Tutor] Searching for email id in MySQL giving wrong results

Python python at venix.com
Mon Jan 23 20:00:52 CET 2006


On Mon, 2006-01-23 at 18:17 +0000, Alan Gauld wrote:
> > On Sun, 2006-01-22 at 21:23 +0300, ZIYAD A. M. AL-BATLY wrote:
> >>         wrong_string = '''SELECT s FROM t WHERE id=%s''' , (email_id)
> > 
> > The string is being used in a call to cursor.execute.  The email_id is a
> > second parameter getting passed to execute.  That is the *correct*
> > approach to use.
> 
> Nope, sorry. 
> This sends the string
> 
> SELECT ..... id=%s something at somewhere.whatever
> 
> ie the %s is kept in the string, not what is wanted.
> 
> The OP must replace the comma with a % character for the string 
> substitution to take place.

The wrong_string line was lifted from the following code in the OP.

        entry = db.cursor()
        entry.execute("""SELECT * FROM contact WHERE email_id = %s""", (s_email,))

The execute method will handle the string substitution.  This is better
than doing it yourself, because execute will deal with any quoting
issues for feeding the data to the database.  

I should have included the original code as I did here.  Sorry if I
created any confusion as related to regular Python string substitution.

It is a very common mistake for people to do the SQL string
interpolation themselves as opposed to leaving it for the execute
method.

> 
> > That is no help in explaining why the SELECT command is failing to
> > return the expected results.
> 
> The rogue %s in the select string will mess things up.
> 
> Alan G.
-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list