我使用PyMySQL通过遍历表名来更新数据,但问题是我能够更新第一个表中的数据,但循环在第一个表之后不起作用
我尝试使用fetchall()来获取表名并按此进行循环,但不起作用
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)
我希望在调用此函数时遍历该数据库中的所有表
发布于 2019-06-16 07:09:57
我不确定你的方法是否是最优的。
在中间的代码块中,employees
是未定义的--应该是emp_lst吗?
您的select语句似乎缩减为
SELECT employee_name FROM $TABLE WHERE attended=0;
然后,您希望遍历每个表并更改其值。您是否考虑过使用UPDATE谓词?https://dev.mysql.com/doc/refman/8.0/en/update.html
UPDATE $table SET attended=True WHERE attended=0;
如果这对您想要的结果有效,那么将为您节省相当多的表扫描和双重处理。
因此,也许您可以按照以下方式重构您的代码:
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)
就这样!
https://stackoverflow.com/questions/56616682
复制相似问题