Another Screwy Problem

J. Cliff Dyer jcd at sdf.lonestar.org
Sat Jan 9 09:07:02 EST 2010


On Sat, 2010-01-09 at 07:59 -0500, Victor Subervi wrote:
> On Fri, Jan 8, 2010 at 4:44 PM, J. Clifford Dyer
> <jcd at sdf.lonestar.org> wrote:
>         Victor Subervi wrote:
>         > Hi;
>         > I have this line of code:
>         >  sql = 'select Name, Price from %sPackages where ID=%s;' %
>         (store, pid)
>         > which prints to this:
>         >  select Name, Price from productsPackages where ID=1;
>         > which when I enter it into the MySQL interpreter gives me
>         this:
>         > mysql> select Name, Price from productsPackages where ID=1;
>         > +------+--------+
>         > | Name | Price  |
>         > +------+--------+
>         > | pkg  | 123.45 |
>         > +------+--------+
>         > 1 row in set (0.00 sec)
>         >
>         > exactly what I expect. However, in my script for some reason
>         it returns
>         > this:
>         > ((1,),)
>         
>         
>         
> First, got your other email. I thought I had executed the statement.
> Oops. Works fine now. Sorry.
>  
>         First, never use string formatting to pass parameters to your
>         database.  Read the MySQLdb documentation (or sqlite, or
>         psycopg2) documentation for reasons why, and how to do it
>         right.
> 
> The only thing I found, which collaborates with something someone else
> taught me on this list about entering binary data, is that one must
> pass the parameters in the execute statement. Is that what you mean?
> If so, I find that for all purposes thus far other than binary data,
> the way I've been doing it seems to work just fine. I would prefer to
> keep doing it that way, because I find putting a print statement
> between the sql= line and the execute statement gives me a good
> opportunity to review the sql statement and catch errors. Is this not
> good practice?
> 
>         
> Thanks.
> beno

This is a horrendous practice.  You leave yourself vulnerable not only
to attacks, but to simple absent-mindedness as well.  Using parameters
in your execute statement will handle all necessary quoting for you,
which eliminates the possibility of a bad query sneaking in.  For more
information, as I mentioned, look up SQL injection.  Also, read this:
http://xkcd.com/327/

Cheers,
Cliff






More information about the Python-list mailing list