tags:

views:

159

answers:

2
query = "SELECT * FROM mytable WHERE time=%s", (mytime)

Currently, I"m doing this, but I want to split it into 2 strings (so I can do them separately)

cursor.execute("SELECT * FROM mytable WHERE time=%s",(mytime))

Then, I want to add a limit %s to it. How can I do that without messing up the %s in mytime?

Edit: I want to concat query2, which has "LIMIT %s, %s"

+1  A: 
cxn.execute("SELECT * FROM mytable WHERE time=%%s LIMIT %d" % (mylimit,), mytime)

Or:

cxn.execute("SELECT * FROM mytable WHERE time=%s" + (" LIMIT %d" % (mylimit,)), mytime)
Ignacio Vazquez-Abrams
+2  A: 

Being wary of SQL injection, you can dynamically compose your query as Ignacio suggests.

>>> qry = 'SELECT t.mycol FROM mytable t WHERE t.mycol = %%s %s' % 'LIMIT %s,%s'

You ask:

How can I do that without messing up the %s in mytime?

Notice that you escape the first %s with an additional %.
That gives you this string (which of course looks lovely as far as the DB-API is concerned):

>>> qry
'SELECT * FROM mytable t WHERE t.mycol = %s LIMIT %s,%s'

Then pass this string and your parameters to the execute() method:

curs.execute(qry, (mytime,1,2,))

HTH

Adam Bernier