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

ZIYAD A. M. AL-BATLY zamb at saudi.net.sa
Mon Jan 23 23:38:57 CET 2006


On Mon, 2006-01-23 at 14:00 -0500, Python wrote:
> 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.
> 
Okay, here's a quote from the definition of "execute()":
        def execute(self, query, args=None):
                """Execute a query.
                
                query -- string, query to execute on server
                args -- optional sequence or mapping, parameters to use with query.
                
                Note: If args is a sequence, then %s must be used as the
                parameter placeholder in the query. If a mapping is
                used,
                %(key)s must be used as the placeholder.
                
                Returns long integer rows affected, if any"""

So, my answer is correct.  And it seems there are other solutions (using
sequences and "%s" (just like Lloyd Kvam said) or "%(key1)s" in case of
passing a mapping sequence (which, I think, is just a dictionary)).

Why it didn't work for him in the first place?  I really don't know.

DISCLAIMER:
        I *NEVER* used "MySQLdb".  I just wanted to help.  The sentence:
                """%s""", (email_id)
        seemed awfully wrong to me, and since nobody replied to him for
        more than a day, I suggested (what seemed to me) the right
        answer.
        
        That's a wrong thing to do since I don't know anything about
        "MySQLdb".  So, I apologise to all of you.

Ziyad.



More information about the Tutor mailing list