威凡网全力打造:网页编程、软件开发编程、平面设计、服务器端开发、操作系统等在线学习平台!学编程,上威凡网!
python教程>> python基础 python进阶 python高级 python技巧
当前位置:首页 > python教程 > python进阶
上一节 下一节
 Python MySQL Delete From
  • mysql order by

删除记录

您可以使用 "delete from" 语句从已有的表中删除记录:

实例

删除地址为 "mountain 21" 的任何记录:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

sql = "delete from customers where address = 'mountain 21'"

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, "record(s) deleted")

运行实例

重要:请注意语句 mydb.commit()。需要进行更改,否则表不会有任何改变。

请注意 delete 语法中的 where 子句:where 子句指定应删除哪些记录。如果省略 where 子句,则将删除所有记录!

防止 sql 注入

在 delete 语句中,转义任何查询的值也是一种好习惯。

此举是为了防止 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 = "delete from customers where address = %s"
adr = ("yellow garden 2", )

mycursor.execute(sql, adr)

mydb.commit()

print(mycursor.rowcount, "record(s) deleted")

运行实例

  • mysql order by

申明:本教程内容由威凡网编辑整理并提供IT程序员分享学习,如文中有侵权行为,请与站长联系(QQ:254677821)!
上一节 下一节
相关教程  
其他教程  
python基础
python进阶
python高级
python技巧

违法和不良信息举报中心】邮箱:254677821@qq.com
Copyright©威凡网 版权所有 苏ICP备2023020142号
站长QQ:254677821