当前位置:Gxlcms > 数据库问题 > Python MySQL Delete

Python MySQL Delete

时间:2021-07-01 10:21:17 帮助过:15人阅读


章节

  • Python MySQL 入门
  • Python MySQL 创建数据库
  • Python MySQL 创建表
  • Python MySQL 插入表
  • Python MySQL Select
  • Python MySQL Where
  • Python MySQL Order By
  • Python MySQL Delete
  • Python MySQL 删除表
  • Python MySQL Update
  • Python MySQL Limit
  • Python MySQL Join

删除记录

可以使用“DELETE FROM”语句,从现有表中删除记录:

示例

删除地址为“Mountain 21”的记录:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  database="mydatabase"
)

mycursor = mydb.cursor()

sql = "DELETE FROM customers WHERE address = 'Mountain 21'"

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, " 条记录删除")

注意: 数据库修改后,需要使用mydb.commit()语句提交,不提交,修改不会生效。

注意DELETE语句中的WHERE子句: WHERE子句指定应该删除哪些记录。如果省略WHERE子句,将删除所有记录!

防止SQL注入

在delete语句中,为了防止SQL注入,通常应该转义查询值。

SQL注入是一种常见的web黑客技术,用于破坏或误用数据库。

mysql.connector 模块有方法可以转义查询值:

示例

使用占位符%s方法转义查询值:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="你的用户名",
  passwd="你的密码",
  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, " 条记录删除")

Python MySQL Delete

标签:mysq   print   customers   page   com   指定   article   哪些   ddr   

人气教程排行