2013-08-06 76 views
1

我想在sqlite3中存儲類列表對象。 我對查詢列表內容不感興趣,所以blob單元格很好。 搜索不同的方法後,我想出了使用結構。 但是,這是行不通的:以sqllite3存儲數據序列(blob)

import sqlite3 
import datetime 
import time 
import struct 

# Create DB 
dbpath = './test.db' 
db = sqlite3.connect(dbpath) 
cursor=db.cursor() 
cursor.execute("""   
    CREATE TABLE IF NOT EXISTS trials (
    timestamp INTEGER PRIMARY KEY, emg BLOB) """) 
cursor.execute ('DELETE FROM trials') 
# Define vars 
now = datetime.datetime.now() 
timestamp = time.mktime(now.timetuple()) 
emg = range(200) 
s = struct.pack('f'*len(emg), *emg) 

# Store vars 
cursor.execute(""" 
    INSERT INTO trials VALUES (?,?)""", (timestamp,s)) 
db.commit() 

# Fetch vars 
cursor.execute(""" 
    SELECT * FROM trials WHERE timestamp = ?""", (timestamp,)) 
out = cursor.fetchone() 
s1 = out[1] 
print(s1) # --> EMPTY 
emg1=struct.unpack('f'*(len(s1)/4), s1) 
print(emg1) # -->() 

# However 
emg0=struct.unpack('f'*(len(s)/4), s) 
print(emg0) # --> (0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0.... 

任何想法是什麼,我做錯了,或建議,更好/更pythonish的方式來保存數據的長序列? 謝謝!

回答

0

我不確定什麼不是特別爲你工作 - 如果我替換除法運算符(/用//),我在Python 3上得到相同的輸出。

但是,也許pickle更適合您的問題比結構?這裏是你的代碼修改使用它。最後一行檢查以確保存儲和檢索的值與原始值相同。 進口sqlite3的 進口日期時間
進口時間 進口泡菜

# Create DB 
dbpath = './test.db' 
db = sqlite3.connect(dbpath) 
cursor=db.cursor() 
cursor.execute("""   
    CREATE TABLE IF NOT EXISTS trials (
    timestamp INTEGER PRIMARY KEY, emg BLOB) """) 
cursor.execute ('DELETE FROM trials') 
# Define vars 
now = datetime.datetime.now() 
timestamp = time.mktime(now.timetuple()) 
emg = list(range(200)) 
s = pickle.dumps(emg, pickle.HIGHEST_PROTOCOL) 

# Store vars 
cursor.execute(""" 
    INSERT INTO trials VALUES (?,?)""", (timestamp,s)) 
db.commit() 

# Fetch vars 
cursor.execute(""" 
    SELECT * FROM trials WHERE timestamp = ?""", (timestamp,)) 
out = cursor.fetchone() 
s1 = out[1] 
emg1 = pickle.loads(s1) 

# Test equality 
print(emg1 == emg) 
+0

味酸對我的作品definetly更好,因爲它允許也不同類型的對象存儲與代碼沒有任何變化!謝謝! – pief