Python 更新表
Python基础 2022-06-06 12:58:26小码哥的IT人生shichen
Python 更新表
更新表
您可以使用 "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")
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
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 注入
在 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")
完整实例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
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")