我想在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....
你知道我做错了什么吗,或者推荐一种更好/更平淡的方式来保存长序列的数据?谢谢!
发布于 2013-08-06 12:58:20
具体而言,我不知道什么不适合您--如果我用//替换除法操作符( / /),我在Python 3上得到了相同的输出。
但是,也许pickle
比struct更适合您的问题?下面是您修改的代码以使用它。最后一行检查以确保存储和检索的值与原始值相同。导入sqlite3导入日期时间
import time import pickle
# 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)
https://stackoverflow.com/questions/18080081
复制相似问题