我想在sqlite3中存储类似列表的对象。 我对查询列表的内容不感兴趣,所以blob单元格可以。 在搜索了不同的方法之后,我想到了使用一个struct。 但是,它不起作用:
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的方法来保存长序列的数据吗? 谢谢!在
我不确定有什么不适合您—如果我替换除法运算符(/替换为//),在Python3上得到相同的输出。在
然而,也许
pickle
比struct更适合您的问题?这是修改后的代码以使用它。最后一行检查以确保存储和检索的值与原始值相同。 导入sqlite3 导入日期时间导入时间 进口腌菜
相关问题 更多 >
编程相关推荐