Mr. P
Mr. P

Reputation: 23

Insert record into SQLite table with large number of columns

Using Python 2.7.6, if I want to add a single record to an SQLite database using values (e.g. integers) stored in variables, I can do the following:

import sqlite3
w,x,y,z = 0,1,2,3
conn = sqlite3.connect('mydb.db')
conn.execute('CREATE TABLE IF NOT EXISTS data (v1 INTEGER, v2 INTEGER, v3 INTEGER, v4 INTEGER)')
conn.execute('INSERT INTO data VALUES (?,?,?,?)', (w,x,y,z))
conn.commit()
conn.close()

What if the number of values to be inserted in the single record is large (e.g. 100, 200, arbitrary?), and are stored in a sequence or collection like a list, queue, array, etc? Is there a way to modify the INSERT syntax above so that I can specify only the name of the collection rather than a very long itemized list? And is any particular collection type more convenient to use in this scenario?

Edit: The above code example has four values going into four columns in the table. For the question about the larger data, assume that there are as many columns in the database table as there are values to insert.

Edit2: I want to insert a single record consisting of the values in a large collection. I do not want to insert many records (e.g. executemany).

Upvotes: 2

Views: 1784

Answers (1)

CL.
CL.

Reputation: 180070

In your code, (w,x,y,z) is a four-element tuple; that's your variable.

You could just as well use a list instead:

my_little_list = [w, x, y, z]
cursor.execute("...", my_little_list)

Upvotes: 2

Related Questions