2017-02-11 59 views
0

我与一个问题like in this主题。我尝试了“unixepoch”,但即便如此,我的记录返回NoneSQL strftime与python和sqlite3返回无

运行SQL下面直接sqliteman,我有作为回报,我希望

SELECT sum(value) 
FROM customers 
WHERE customer_id = 1 
    AND devolution = 'No' 
    AND strftime('%Y', delivery_date) IN ('2016') 

的价值,但是,在当蟒蛇,我没有得到从print self.rec[0]

def get_total_from_last_year(self): 
    self.now = datetime.datetime.now() 
    self.lastYear = self.now.year -1 

    self.con = sqlite3.connect(database.name) 
    self.cur = self.con.cursor() 
    self.sql = """SELECT sum(value) 
     FROM customers 
     WHERE customer_id=? 
     AND devolution='No' 
     AND strftime('%%Y',delivery_date) IN(%s) """ %(str(self.lastYear)) 
    self.cur.execute(self.sql, str(customerID)) 
    self.rs = self.cur.fetchall() 

    for self.rec in self.rs: 
     print self.rec[0] 

回报有人可以帮我? 非常感谢。在python

回答

1

您的查询字符串是错误的:

  • 你不需要双重%,为新年。
  • 如果您想添加参数,则必须引用条件为“IN”的年份。
  • 你不应该以这种方式应用params,而是让sqlite为你获得类型,就像你为customerId所做的那样。

这应该现在的工作:

self.cur.execute("SELECT sum(value) \ 
    FROM customers \ 
    WHERE customer_id=? \ 
    AND devolution='No' \ 
    AND strftime('%Y',delivery_date) IN (?)", (customerID, self.lastYear)) 

你不应该需要转换的customerID到STR(),sqlite3的应该能为你做它。

请注意,为了清楚起见,我在行尾添加了\(如我打破了这些界限),您可能不需要它们。

+1

检查你周围'“否”的引号。你会想保留三重引号。 – Schwern

+0

完成,发布答案后发现。感谢您的提示;-) – mydaemon

+0

现在,它使用单引号,并将customerID和self.lastYear转换为str()。谢谢! –