Python tablo güncelleme
- 上一页 MySQL Drop Table
- 下一页 MySQL Limit
Tablo güncelleme
Tablodaki mevcut kayıtları güncellemek için "UPDATE" cümlesini kullanabilirsiniz:
实例
Adres sütunundaki "Valley 345"'i "Canyoun 123" ile değiştirin:
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")
Önemli:Lütfen cümleye dikkat edin mydb.commit()
Değişmesi gerekiyorsa, tablo değişmeyecek.
Lütfen UPDATE dilbilgisiindeki WHERE ifadesine dikkat edin: WHERE ifadesi güncellenmesi gereken kayıtları belirtir. WHERE ifadesi atlanırsa, tüm kayıtlar güncellenecektir!
防止 SQL 注入
在 update 语句中,转义任何查询的值都是个好习惯。
此举是为了防止 SQL 注入,这是一种常见的网络黑客技术,可以破坏或滥用您的数据库。
mysql.connector 模块使用占位符 %s
来转义 delete 语句中的值:
实例
使用占位符 %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")
- 上一页 MySQL Drop Table
- 下一页 MySQL Limit