迭代 table 个名称并更新查询

Iterating over table names and updating queries

我正在使用 PyMySQL 通过遍历 table 个名称来更新数据,但问题是我只能从第一个 table 更新数据 在第一个 table

之后循环不工作

我试过使用 fetchall() 获取 table 名称并以此循环,但没有成功

def update():
    global table_out
    global i
    cursor.execute("USE company;")
    cursor.execute("SHOW TABLES;")
    lst=[]
    for table_name in cursor:
         lst.append(table_name)
         emp_list=lst[0][0]
         print(emp_list)
         i=0
         while i<=len(lst)-1:
             state="""SELECT `employee_name` from `%s` WHERE attended=0 """%(employees)
             out=cursor.execute(state)
             result=cursor.fetchall()
             i+=1
             for records in result:
                 table_out=''.join(records)
                 print(table_out)
                 db.commit()
                 try:

                    sql="""UPDATE `%s` SET `attended` = True WHERE `employee_name` = '%s' ;"""%(emp_list,table_out)
                         cursor.execute(sql)

我希望在调用此函数时遍历该数据库中的所有 table

我不确定你的方法是否是最优的。

[在你的中间块中,employees 未定义 - 应该是 emp_lst 吗?]

您的 select 语句似乎减少到

SELECT employee_name FROM $TABLE WHERE attended=0;

然后您要遍历每个 table 并更改值。您是否考虑过改用 UPDATE 动词? https://dev.mysql.com/doc/refman/8.0/en/update.html

UPDATE $table SET attended=True WHERE attended=0;

如果这对您想要的结果有效,那么这将为您节省不少 table 扫描和双重处理。

所以也许您可以按照这些行重构您的代码:

def update_to_True():
# assume that cursor is a global
cursor.execute("USE company;")
tables = cursor.execute("SHOW TABLES;").fetchall()
for el in tables:
    STMT="""UPDATE {0} SET attended=True WHERE attended=0;".format(el)
    res = cursor.execute(el)
    # for debugging....
    print(res)

就是这样!