2017-02-11 31 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()。謝謝! –