1

我想在 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....

关于我做错了什么的任何想法,或者关于保存长数据序列的更好/更pythonish方式的建议?谢谢!

4

1 回答 1

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)
于 2013-08-06T12:58:20.587 回答