Bài 7 – Xóa dữ liệu của bảng trong cơ sở dữ liệu MySQL bằng Python

Để có thể xóa đi một vài bản ghi thỏa mãn điều kiện nào đó, trong SQL ta sử dụng lệnh DELETE FROM. Trong Python dãy câu lệnh xóa các bản ghi thỏa mãn điều kiện như sau:

Kết nối Python với cơ sở dữ liệu MySQL

Xóa các bản ghi thỏa mãn điều kiện

– Dạng không thay thế điều kiện

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="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")

Lưu ý:
– Câu lệnh mydb.commit()phải được thực hiện để việc xóa bản ghi có hiệu lực nếu không dữ liệu sẽ không được thay đổi.
– Điều kiện trong WHERE để xác định các bản ghi thỏa mãn điều kiện sẽ bị xóa, nếu không có điều kiện trong WHERE thì tất cả các bản ghi của bảng đều bị xóa hết.

– Dạng thay thế giá trị của điều kiện

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="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") 

Xóa bảng trong cơ sở dữ liệu

Để xóa bảng trong cơ sở dữ liệu MySQL ta sử dụng lệnh SQL là DROP TABLE

import mysql.connector

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

mycursor = mydb.cursor()

sql = "DROP TABLE customers"

mycursor.execute(sql)

Để tránh quá trình xóa bị lỗi nếu bảng cần xóa không tồn tại ta sử dụng thêm từ khóa IF EXISTS

import mysql.connector

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

mycursor = mydb.cursor()

sql = "DROP TABLE IF EXISTS customers"

mycursor.execute(sql)

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *