1
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"

2
  • Can you also post the code you are using to execute the query? Commented Mar 31, 2010 at 0:50
  • 9
    I love SQL injection. Commented Mar 31, 2010 at 1:35

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.