您可以使用来注册新的
array数据类型
sqlite3:
import sqlite3import numpy as npimport iodef adapt_array(arr): """ http://stackoverflow.com/a/31312102/190597 (SoulNibbler) """ out = io.BytesIO() np.save(out, arr) out.seek(0) return sqlite3.Binary(out.read())def convert_array(text): out = io.BytesIO(text) out.seek(0) return np.load(out)# Converts np.array to TEXT when insertingsqlite3.register_adapter(np.ndarray, adapt_array)# Converts TEXT to np.array when selectingsqlite3.register_converter("array", convert_array)x = np.arange(12).reshape(2,6)con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)cur = con.cursor()cur.execute("create table test (arr array)")
使用此设置,您可以简单地插入NumPy数组,而无需更改语法:
cur.execute("insert into test (arr) values (?)", (x, ))
并直接从sqlite作为NumPy数组检索数组:
cur.execute("select arr from test")data = cur.fetchone()[0]print(data)# [[ 0 1 2 3 4 5]# [ 6 7 8 9 10 11]]print(type(data))# <type 'numpy.ndarray'>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)