我知道SO上有一个类似的问题,基本上是在问同样的问题。然而,我似乎收到了一条错误消息。让我解释一下。
为了测试用Sqlite3数据库存储和检索Python日期对象的想法,我创建了一个小的测试脚本:
import sqlite3
import datetime
conn = sqlite3.connect("test.db")
conn.execute('''CREATE TABLE TEST
(
ID TEXT PRIMARY KEY NOT NULL,
DATE TIMESTAMP
);''')
conn.commit()
mydate = datetime.date(2014,4,28)
myid = 'test'
conn.execute("INSERT INTO TEST (ID,DATE)
VALUES(?,?)",[myid,mydate])
conn.commit()
conn.close()
conn = sqlite3.connect("test.db")
cursor = conn.execute("SELECT ID,DATE from TEST")
for row in cursor:
retrievedDate = row[1]
print retrievedDate,type(retrievedDate)
conn.close()
代码有效,但检索到的日期在unicode
中。
我从上面的链接中发现,如果没有detect_types=sqlite3.PARSE_DECLTYPES
参数,sqlite将返回unicode。所以,我把代码改成这样:
...
conn = sqlite3.connect("test.db",detect_types=sqlite3.PARSE_DECLTYPES)
cursor = conn.execute("SELECT ID,DATE from TEST")
for row in cursor:
retrievedDate = row[1]
print retrievedDate,type(retrievedDate)
...
但现在它给了我这个错误信息:
File "C:Python27libsqlite3dbapi2.py", line 66, in convert_timestamp
datepart, timepart = val.split(" ")
ValueError: need more than 1 value to unpack
问题出在哪里?
您将列声明为时间戳:
conn.execute('''CREATE TABLE TEST
(
ID TEXT PRIMARY KEY NOT NULL,
DATE TIMESTAMP
);''')
改为键入DATE
;Python根据列类型选择一个转换器,TIMESTAMP
在这里触发了错误的转换器。
演示:
>>> import sqlite3
>>> import datetime
>>> conn = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
>>> conn.execute('''CREATE TABLE TEST (ID TEXT PRIMARY KEY NOT NULL, DATE DATE)''')
<sqlite3.Cursor object at 0x104a5adc0>
>>> conn.commit()
>>> conn.execute("INSERT INTO TEST (ID,DATE) VALUES (?, ?)",
... ('foo', datetime.date(2014,4,28)))
<sqlite3.Cursor object at 0x104a5ae30>
>>> conn.commit()
>>> cursor = conn.execute("SELECT ID,DATE from TEST")
>>> for row in cursor:
... print row
...
(u'foo', datetime.date(2014, 4, 28))
或者,在方括号中的SELECT
查询中包括类型名称:
cur.execute('SELECT ID, DATE [date] from TEST')