Python将日期存储和检索到Sqlite3数据库中

时间:2014-04-30 15:41:18

标签: python python-2.7 datetime sqlite

我知道这个similar question on SO基本上是在询问同样的事情。但是,我似乎收到了一条错误消息。让我解释一下。

为了测试使用Sqlite3数据库存储和检索Python Date对象的想法,我创建了这个小测试脚本:

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:\Python27\lib\sqlite3\dbapi2.py", line 66, in convert_timestamp
    datepart, timepart = val.split(" ")
ValueError: need more than 1 value to unpack

导致问题的原因是什么?

1 个答案:

答案 0 :(得分:1)

您将列声明为时间戳:

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')