如何使用python运行基于select查询结果的update SQL查询



我正试图根据使用python的选择查询的结果更新sql表中的一行。如何添加相同,以便如果在select查询中找到结果,我们应该能够运行update query并打印为列表更新,如果没有退出,说没有找到更新表

cursor = conn.cursor()
cursor.execute(
"select * from student where email = 'xyz.com'"
)
student = cursor.fetchall()
print(student)
for row in student:
cursor.execute(" Update student set value = 0 where email = 'xyz.com'")

您不需要执行单独的SELECT,您可以使用OUTPUT子句让UPDATE语句从更新的行返回值。例如,使用pyodbc:

sql = """
UPDATE student SET value = 0
OUTPUT INSERTED.student_number
WHERE email = 'xyz.com' AND (value <> 0 OR value IS NULL)
"""
student_numbers = crsr.execute(sql).fetchall()
print(student_numbers)  # [(1001, ), (1003, )]

最新更新