小码哥的IT人生

Python MySQL Delete From

Python基础 2022-06-06 12:58:19小码哥的IT人生shichen

Python MySQL Delete From

删除记录

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

完整实例:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  passwd="mypassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = 'Park Lane 38'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
  print(x)

重要:请注意语句 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")

完整实例:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  passwd="mypassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
  print(x)

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024