I'm using SQLite3 in Python to build a database and tables. I want to create a table according to the value of a variable (name: A). I found this (answer) and it says "Unfortunately, tables can't be the target of parameter substitution". And the full table name should be like "table_"+str(A). I tried several methods:
new_field = 'my_1st_column'
field_type = 'INTEGER'
tablename = "table_"+str(A)
databasecur.execute('CREATE TABLE IF NOT EXISTS {tn} ({nf} {ft})' .format(tn=tablename, nf=new_field, ft=field_type))
or
databasecur.prepare("CREATE TABLE IF NOT EXISTS" + tablename + "(col1, col2)")
All of them are not working. So right now the way I can figure out is like:
A=1140
tablelist = [1140, 1150, 1160, 1170,....]
tablenum = tablelist.index(A)
con = sqlite3.connect('test.db')
cur = con.cursor()
if tablenum == 0:
cur.execute("create table if not exists table_1140 (col1, col2)")
elif tablenum == 1:
cur.execute("create table if not exists table_1150 (col1, col2)")
......
con.close()
Does anyone have more effective way to do this? Thank you very much.