简体   繁体   中英

add multiple columns to an sqlite database in python

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!

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM