【问题标题】:sqlite query with strftime always returns None使用 strftime 的 sqlite 查询总是返回 None
【发布时间】:2014-12-28 15:24:06
【问题描述】:

我有以下功能:

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

当我知道我应该有另一个结果时,它总是返回 None。从print q_totes_1 我得到了我直接在sqlite 上执行的查询,我得到了想要的结果。所有导入都是正确的,因为我已经在同一类的其他函数中成功使用了它们。

我尝试运行没有strftime('%%m',es_date)='%s' 部分的类似查询,它运行正常。

有人可以告诉我我缺少什么吗?

【问题讨论】:

  • 你的意思是 它总是返回 None ?您是否将此代码定义为函数?
  • @Kasra m_totes_1 为无;我也尝试了self.cur.fetchall(),得到了(None,)
  • @Filippos 使用单个 % 并检查
  • @Bhargav Rao 我得到ValueError: unsupported format character 'm' (0x6d) at index 48
  • @Filippos Final """SELECT sum(kaxia) FROM es_data WHERE strftime('%%m',es_date)= ? AND es_orig=1""",(str(i),)

标签: python sqlite strftime


【解决方案1】:

改成

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

您的代码将是

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

您也是 SQL 注入的受害者。 (在 DB 中始终使用 ? 符号)

【讨论】:

  • 复制并粘贴到我的代码中。仍然收到operation parameter must be str or unicode
  • 所以我的代码现在看起来像 self.cur.execute( """SELECT sum(kaxia) FROM es_data WHERE strftime('%m',es_date)= ? AND es_orig=1""",(str(i),) ) # print q_totes_1 m_totes_1=self.cur.fetchone()[0] print m_totes_1 但仍然是 print m_totes_1 输出 None
  • 再次输出None。我知道它与strftime 有关,因为没有它我的初始代码运行顺利......
  • @Filippos 你确定它必须返回一些东西吗?或者数据库中没有数据。我检查了查询,它对我有用
  • 所以我的代码现在看起来像: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),) ) for i in x: print (i) m_totes_1=x.fetchone()[0] print m_totes_1 if m_totes_1 is None: m_totes_1=0.0,结果是TypeError: 'NoneType' object has no attribute '__getitem__' (None,)。抱歉,在 cmets 中格式化没有帮助
【解决方案2】:

最后我得到了执行的查询,令我失望的是它非常简单:

查询应该具有这种格式(我倾向于忽略注入的可能性,因为与数据库的唯一交互将通过 python 应用程序):

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

缺少'unixepoch' 修饰符似乎输出了None 值结果。

非常感谢所有试图提供帮助的人...

【讨论】:

  • 太棒了。接受您的正确答案并将此问题标记为已回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-14
相关资源
最近更新 更多