2014-04-30 81 views
0

我知道這similar question on SO這基本上是問同樣的事情。但是,我似乎收到錯誤消息。讓我解釋。蟒蛇存儲和檢索日期到Sqlite3數據庫

爲了測試與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

你聲明的列是一個時間戳:

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

它的工作原理!鏈接到我的帖子上的另一個SO問題使用'timestamp'而不是'DATE'。但'DATE'似乎對我來說工作得很好。謝謝 –

+1

@ChrisAung:'timestamp'代替'datetime.datetime'對象。 –