我试图在Python中使用SQLite通过变量创建表

时间:2017-05-12 09:10:12

标签: python sqlite

我在Python中使用SQLite3来构建数据库和表。我想根据变量的值创建一个表(名称:A)。我找到了这个(answer),它说"不幸的是,表格不能成为参数替换的目标"。全表名称应该像" table _" + str(A)。我尝试了几种方法:

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))

databasecur.prepare("CREATE TABLE IF NOT EXISTS" + tablename + "(col1, col2)")

所有这些都不起作用。所以现在我能想出来的方式就像:

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()

有没有人有更有效的方法来做到这一点?非常感谢你。

0 个答案:

没有答案