簡體   English   中英

帶有python和sqlite3的SQL strftime返回None

[英]SQL strftime with python and sqlite3 returns None

我遇到類似此主題的問題。 並且我嘗試了'unixepoch',但是即使如此,我的記錄集仍返回None

直接在sqliteman中運行以下sql,我得到的回報是我期望的值

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

但是,當在python中時,我從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中的查詢字符串是錯誤的:

  • 年度不需要雙%。
  • 如果要在執行操作時添加參數,則必須使用條件“ 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應該可以為您完成此操作。

請注意,為了清楚起見,我在行的末尾添加了\\(因為我在破壞行),您可能不需要它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM