Python MySQL Delete

Python MySQL 教程

相关推荐

Python MySQL Delete

2019年6月4日

 意见反馈

删除记录

可以使用“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, " 条记录删除")

复制


Doc navigation

← Python MySQL Order By

Python MySQL 删除表 →

猜你喜欢

转载自blog.csdn.net/matthewwu/article/details/93334586