4

I want to create a table with multiple columns, say about 100 columns, in an sqlite database. Is there a better solution than naming each column individually? I am trying the following:

conn = sqlite3.connect('trialDB')
cur = conn.cursor()

listOfVars = ("added0",)
for i in range(1,100):
    newVar = ("added" + str(i),)
    listOfVars = listOfVars + newVar
print listOfVars

for i in listOfVars:
    cur.execute('''ALTER TABLE testTable ADD COLUMN ? TEXT''',(i,))

conn.commit()    
cur.close()
conn.close()

But I get the following error:

OperationalError: near "?": syntax error

Can someone please suggest how I can do this? Thanks!

3
  • 1
    I don't think placeholders work for column or table names. Commented Oct 21, 2010 at 13:48
  • Just to confirm SilentGhost - placeholders definitely do not work for column or table names. Commented Oct 21, 2010 at 14:06
  • Thanks, SilentGhost and Matthew Commented Oct 21, 2010 at 14:31

1 Answer 1

6

I guess you could do it through string formatting, like this :

for i in listOfVars:
    cur.execute('''ALTER TABLE testTable ADD COLUMN %s TEXT''' % i)

But having 100 columns in a sqlite db is certainly not common, are you sure of having a proper db design ?

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

1 Comment

I am running some simulations, each of which outputs a data matrix with about 1500 rows and 200 columns. If I output the data to a .csv file it is about 3mb. I was wondering if using an sqlite database will make the whole thing efficient. Thanks for your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.