在sqlite3语句中使用Python变量

时间:2014-05-30 13:34:35

标签: python sqlite

我想在sql请求中使用python变量。

ss_length = 15

我试过了:

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)

和这个

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)

这两个人中没有一个为我工作。

他们有什么问题?

1 个答案:

答案 0 :(得分:2)

我用过它并且它有效,谢谢大家的回复:

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