我创建了三个表格,并且我想创建一个函数,该函数根据其中一个变量值使用变量值填充表格,因为它们由另一个函数更新。如何将表名设置为变量并将变量插入到python中的sqlite表中?
c.execute('CREATE TABLE IF NOT EXISTS unu (id INTEGER PRIMARY KEY, item1 TEXT, item2 INT)')
c.execute('CREATE TABLE IF NOT EXISTS doi (id INTEGER PRIMARY KEY, item1 TEXT, item2 INT)')
c.execute('CREATE TABLE IF NOT EXISTS trei (id INTEGER PRIMARY KEY, item1 TEXT, item2 INT)')
update_tables()
def tablepopulate(table):
query = 'SELECT item2 FROM {} ORDER BY id DESC LIMIT 1'.format(table)
insert ='INSERT INTO {} (item1,item2) VALUES (?,?)'.format(table)
c.execute(query)
xy=c.fetchone()
if xy == None :
c.execute(insert,(item1, item2))
elif xy[1] == 0
c.execute(insert,(item1, item2))
try:
tablepopulate("unu")
except:
try:
tablepopulate("doi")
except:
try:
tablepopulate("trei")
except:
print("all tables are populated")
此代码不会给我任何错误,但它不会填充表
它不会显示任何错误,因为您明确隐藏它们。删除所有这些尝试/除外,并显示实际的错误是什么。 –
这里有很多东西。在创建表之后,你可能需要'conn.commit()'更改。但是''SELECT item2 FROM {} ORDER BY id DESC LIMIT 1'.format(table)'在'{}'后面需要一个空格,然后是'INSERT INTO {}(?,?)VALUES(item1,item2 )'.format(table)'是回到前面,可能应该是''INSERT INTO {}(item1,item2)VALUES(?,?)'.format(table)'。然后,'item1'和'item2'没有在'tablepopulate()'中定义。 – roganjosh
小心输入错误:'CREATE TABLE IF NOT EXIST(S)','if xy =(=)None:' – PRMoureu