Python insert numpy array into sqlite3 database -
i'm trying store numpy array of 1000 floats in sqlite3 database keep getting error "interfaceerror: error binding parameter 1 - unsupported type".
i under impression blob data type doesn't work numpy array. here's tried:
import sqlite3 sql import numpy np con = sql.connect('test.bd',isolation_level=none) cur = con.cursor() cur.execute("create table foobar (id integer primary key, array blob)") cur.execute("insert foobar values (?,?)", (none,np.arange(0,500,0.5))) con.commit() is there module can use numpy array table? or can convert numpy array form in python (like list or string can split) sqlite accept? performance isn't priority. want work!
thanks!
you register new array data type sqlite3:
import sqlite3 import numpy np import io def 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 text when inserting sqlite3.register_adapter(np.ndarray, adapt_array) # converts text np.array when selecting sqlite3.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)") with setup, can insert numpy array no change in syntax:
cur.execute("insert test (arr) values (?)", (x, )) and retrieve array directly sqlite numpy array:
cur.execute("select arr 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'>
Comments
Post a Comment