Python sqlite比较在查询中存储为文本的日期

时间:2019-06-19 18:41:05

标签: python python-2.7 sqlite

我正在使用Python,并已在sqlite中建立了一个表。我没有意识到Python具有sqlite的时间戳字段类型,所以我将其存储为文本。

下面是我的代码和结果。.表中显示的唯一日期是2019-06-18,但查询返回的是2019-06-19 ...不知道为什么

import sqlite3
# Connecting to the database file
sqlite_file = 'insta.sqlite'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()

# Get all rows
c.execute("SELECT * FROM daily_counts")
count_row = c.fetchall()
for row in count_row:
    print(row)

# Get Daily Count
c.execute('SELECT count FROM daily_counts where current_date = ? and client_id = ? and metric = ?',
    ('2019-06-18', 0, 'C'))
count_row = c.fetchall()
print(count_row)

# Get Daily Count
c.execute('SELECT count FROM daily_counts where current_date = ? and client_id = ? and metric = ?',
    ('2019-06-19', 0, 'C'))
count_row = c.fetchall()
print(count_row)

# Get Daily Count
c.execute('SELECT count FROM daily_counts where current_date = ? and client_id = ? and metric = ?',
    ('2019-06-20', 0, 'C'))
count_row = c.fetchall()
print(count_row)

结果:(请注意,当条件为19时,它将返回18的结果,而18则不返回结果。)

(0, u'2019-06-18', u'A', 2)
(0, u'2019-06-18', u'B', 6)
(1, u'2019-06-18', u'C', 180)
(1, u'2019-06-18', u'D', 258)
(1, u'2019-06-18', u'E', 111)
(0, u'2019-06-18', u'C', 180)
(1, u'2019-06-18', u'F', 3)

[]

[(180,)]

[]

我假设我应该使用时间戳记字段类型而不是文本?但是我仍然希望这能奏效

1 个答案:

答案 0 :(得分:1)

current_datesqlite reserved word

在sql字符串的列名(例如"current_date")中添加双引号或反引号,您应该会得到预期的结果。