Python MySQL 更新记录
-
更新记录
您可以使用“UPDATE”语句来更新表中的现有记录:将地址列从“Valley 345”覆盖为“Canyoun 123”:import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) affected")
重要提示!:请注意以下声明: mydb.commit()。需要进行更改,否则将不对表进行任何更改。
请注意UPDATE语法中的WHERE子句: WHERE子句指定应更新的记录。如果省略WHERE子句,所有记录将被更新!
-
防止SQL注入
通过使用%s占位符方法转义值:import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() sql = "UPDATE customers SET address = %s WHERE address = %s" val = ("Valley 345", "Canyon 123") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record(s) affected")