1

I am trying to figure out a way to put a two dimensional array (using python) into an sqlite database. My array:

['hello', 'hello', 'hello'], ['hello', 'hello', 'hello']

What I want is for each tuple of 'hello's would a new row with each 'hello' being its own attribute. I'm not sure what I'm trying to do is even possible (I hope it is). I tried following a few other posts but I keep getting the error:

sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

Does anyone know how to insert a multidimensional array into a sqlite database? Any help would be appreciated. Here is my code:

import sqlite3

array2d = [['hello' for x in xrange(3)] for x in xrange(3)] 

var_string = ', '.join('?' * len(array2d))

conn = sqlite3.connect('sample.db')
c = conn.cursor()

c.execute('''CREATE TABLE sample (Name TEXT, Line_1 TEXT, Line_2 TEXT)''')

query_string = 'INSERT INTO sample VALUES (%s);' % var_string

c.execute(query_string, array2d)

1 Answer 1

2

Use the cursor.executemany() method to insert a sequence of rows in one go:

query_string = 'INSERT INTO sample VALUES (?, ?, ?)'

c.executemany(query_string, array2d)
conn.commit()

Don't forget to conn.commit() the transaction.

I've not bothered with formatting the SQL parameters here, for demonstration purposes; you don't really want to do so here anyway, as your number of columns is fixed at well (from the CREATE TABLE definition).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for response. I got rid of the error message but I when look into sample.db using SQLite Database Browser the data fields are empty.
You need to commit as well. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.