在sqlite3(blob)中存储数据序列

时间:2013-08-06 12:23:51

标签: python sqlite blob

我想在sqlite3中存储类似列表的对象。 我对查询列表的内容不感兴趣,所以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....

有关我做错了什么的建议,或者建议采用更好/更诡异的方式来保存长序列数据? 谢谢!

1 个答案:

答案 0 :(得分:0)

我不确定什么不适合你 - 如果我替换除法运算符(/ //),我在Python 3上得到相同的输出。

然而,也许pickle更适合你的问题而不是结构?以下是您修改后使用它的代码。最后一行检查以确保存储和检索的值与原始值相同。     import 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)