求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Modeler   Code  
会员   
要资料
 
追随技术信仰

随时听讲座
每天看新闻
 
 
Python MySQL教程
1. Python_MySQL入门
2. Python 创建数据库
3. Python 创建表
4. Python 插入表
5. Python 从表中选取
6. Python 使用筛选器来选取
7. Python 结果排序
8. Python 删除记录
9. Python 删除表
10. Python 更新表
11. Python 限定结果
12. Python 加入
 

 
目录
Python 更新表
42 次浏览
4次  

更新表

您可以使用 "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 注入

在 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")

运行实例 »


您可以捐助,支持我们的公益事业。

1元 10元 50元





认证码: 验证码,看不清楚?请点击刷新验证码 必填



42 次浏览
4次