sqlite query with strftime always returns None

≯℡__Kan透↙ 提交于 2019-12-14 02:36:41

问题


I have the following function:

for i in range(1,13):
        q_totes_1="""SELECT sum(kaxia) FROM es_data WHERE strftime('%%m',es_date)='%s' AND es_orig=1"""%(str(i))
        self.cur.execute(q_totes_1)
        m_totes_1=self.cur.fetchone()[0]
        print q_totes_1
        if m_totes_1 is None:
            m_totes_1=0.0

It always returns None while I know that I should have another result. From the print q_totes_1 I get the query which I execute straightly on sqlite and I get the desired result. All the imports are correct as I already have used them successfully in other functions of the same class.

I tried running a similar query without the strftime('%%m',es_date)='%s' portion and it run correctly.

Can somebody give me a hint of what I'm missing?


回答1:


Change it to

self.cur.execute( """SELECT sum(kaxia) FROM es_data WHERE strftime('%m',es_date)= ? AND es_orig=1""",(str(i),) )

Your code will be

for i in range(1,13):
    x = self.cur.execute( """SELECT sum(kaxia) FROM es_data WHERE strftime('%m',es_date)= ? AND es_orig=1""",(str(i),) )
    m_totes_1=x.fetchone()[0]
    print q_totes_1
    if m_totes_1 is None:
        m_totes_1=0.0

You are also a victim of SQL Injection. (Always use ? symbol in DBs)




回答2:


Finally I got the query to execute and to my disappointment it was annoyingly simple:

The query should have this format (I tend to ignore the possibility of injections as the only interaction with the DB will be through the python app):

SELECT sum(kaxia) FROM es_data WHERE strftime('%%m',es_date,'unixepoch')= '%s'AND es_orig=1"""%(str(i))

The lack of the 'unixepoch' modifier seemed to output a None value result.

Many thanks to all who tried to help...



来源:https://stackoverflow.com/questions/27677751/sqlite-query-with-strftime-always-returns-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!