MySQLdb select
Peter Abel
PeterAbel at gmx.net
Mon Aug 2 13:08:19 EDT 2004
John Fabiani <jfabiani at yolo.com> wrote in message news:<9RPOc.2792$LI7.1058 at newssvr27.news.prodigy.com>...
> thanks that worked but I don't understand why.
> cursor.execute("SELECT * FROM mytest where address = %s",string1)
> above works but - following your suggestion:
> cursor.execute("SELECT * FROM mytest where address = %s" % string1)
> above does not work. So why did
> cursor.execute("SELECT * FROM mytest where clientID = %d" % numb)
> work???????????????
> john
> F. GEIGER wrote:
>
>>> numb=10
>>> "SELECT * FROM mytest where clientID = %d",numb
('SELECT * FROM mytest where clientID = %d', 10)
The result of the above is a tuple, where the first value is a string
and the second one is an int.
So you call cursor.execute (..) with a two values. The first value is
'SELECT * FROM mytest where clientID = %d' which raises the
exception because %d is never an int.
What you wanted to do is to call cursor.execute (..) with one parameter,
which is a string. So as ohers pointed out you have to use Python's
formatting features to get the desired string:
>>> "SELECT * FROM mytest where clientID = %d" % numb
'SELECT * FROM mytest where clientID = 10'
Even if your first example works from the point of view of SQL
it wouldn't give you the results, you want.
>>> string1='18 Tadlock Place'
>>> "SELECT * FROM mytest where address = %s",string1
('SELECT * FROM mytest where address = %s', '18 Tadlock Place')
That means again, your'e calling cursor.execute (..) with two parameters
where the first one - again - is 'SELECT * FROM mytest where address = %s'
So youre SQL-result should be empty, cause you surely don't have an adress
with the value %s.
So formatting it the right way and adding single quotmarks araound string1
will give you the result you want:
>>> "SELECT * FROM mytest where address = '%s'" % string1
"SELECT * FROM mytest where address = '18 Tadlock Place'"
>>>
Regards Peter
> >
> > "John Fabiani" ... [snip]
More information about the Python-list
mailing list