简体   繁体   English

带有python和sqlite3的SQL strftime返回None

[英]SQL strftime with python and sqlite3 returns None

I am with a problem like in this topic. 我遇到类似此主题的问题。 and I've tried 'unixepoch', but even so, my recordset returns None 并且我尝试了'unixepoch',但是即使如此,我的记录集仍返回None

running the sql below directly in sqliteman, i have as return, the value that I expected 直接在sqliteman中运行以下sql,我得到的回报是我期望的值

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

but, when in python, I get None as return from the print self.rec[0] 但是,当在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]

Someone can help me? 有人可以帮我吗? Thank you very much. 非常感谢你。

Your query string in python is wrong: 您在python中的查询字符串是错误的:

  • You don't need double % for the Year. 年度不需要双%。
  • The year in the condition "IN" must be quoted if you want to add the param as you are doing. 如果要在执行操作时添加参数,则必须使用条件“ IN”的年份。
  • You should never apply params that way, but let sqlite to get the type for you, as you did for customerId. 永远不要那样使用params,而让sqlite为您获取类型,就像为customerId所做的那样。

This should work now: 现在应该可以使用:

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

You should not need to convert customerID to str(), sqlite3 should be able to do it for you. 您不需要将customerID转换为str(),sqlite3应该可以为您完成此操作。

Please note I'm adding \\'s at the end of the lines for the sake of clarity (as I'm breaking the lines), you might not need them. 请注意,为了清楚起见,我在行的末尾添加了\\(因为我在破坏行),您可能不需要它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM