0

I would like to use python variable within a sql request.

ss_length = 15

I tried this :

cursor = db.execute("SELECT SUBSTR(timestamp, 1, %s), count(SUBSTR(timestamp, 1, %s)) FROM tweets GROUP BY SUBSTR(timestamp, 1, %s) ORDER BY count(SUBSTR(timestamp, 1, %s))" % ss_length, ss_length, ss_length, ss_length)

and this

cursor = db.execute("SELECT SUBSTR(timestamp, 1, ?), count(SUBSTR(timestamp, 1, ?)) FROM tweets GROUP BY SUBSTR(timestamp, 1, ?) ORDER BY count(SUBSTR(timestamp, 1, ?))", ss_length, ss_length, ss_length, ss_length)

No one of the two worked for me.

What's wrong with them ?

0

1 Answer 1

2

I used this and it worked, thank you all for your responses:

cursor = db.execute("""SELECT SUBSTR(timestamp, 1, ?), count(SUBSTR(timestamp, 1, ?)) 
                       FROM tweets 
                       GROUP BY SUBSTR(timestamp, 1, ?) 
                       ORDER BY count(SUBSTR(timestamp, 1, ?))
                    """, (ss_length, ss_length, ss_length, ss_length))
Sign up to request clarification or add additional context in comments.

3 Comments

I am not sure why I am obliged to add the last "," after ss_length. Without it, the query don't work.
Yes, it worked without the last comma, but first time I removed it it haven't worked for me.. weird. I'll correct my answer.
In my experience, embedded SQL queries are much easier to manage when split across multiple lines. I took the liberty of reformatting the example, which I think makes it easier to understand.

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.