简体   繁体   中英

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

running the sql below directly in sqliteman, i have as return, the value that I expected

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]

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:

  • 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.
  • You should never apply params that way, but let sqlite to get the type for you, as you did for 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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