Làm cách nào để xóa dữ liệu trong python?

Bài học này trình bày cách thực hiện truy vấn SQL DELETE từ Python để xóa dữ liệu khỏi bảng cơ sở dữ liệu MySQL

Sau khi đọc bài viết này, bạn sẽ có thể xóa một hàng, nhiều hàng và tất cả các hàng, cũng như xóa một cột và nhiều cột khỏi bảng MySQL bằng Python

Đọc thêm

  • Giải bài tập Python MySQL
  • Đọc Hướng dẫn Python MySQL [Hướng dẫn đầy đủ]

Mục lục

điều kiện tiên quyết

Trước khi di chuyển xa hơn, hãy chắc chắn rằng bạn có những điều sau đây tại chỗ. –

  • Tên người dùng và mật khẩu để kết nối MySQL
  • Tên bảng MySQL mà bạn muốn chèn dữ liệu

Để thực hiện thao tác xóa, tôi đang sử dụng bảng Máy tính xách tay có trong máy chủ MySQL của mình

Nếu một bảng không có trong máy chủ MySQL của bạn, bạn có thể tham khảo bài viết của chúng tôi để

Bạn cũng có thể tải xuống tệp truy vấn SQL chứa các truy vấn SQL để tạo bảng và dữ liệu để bạn có thể sử dụng bảng này cho các thao tác INSERT của mình

Bảng máy tính xách tay MySQL có dữ liệu

Ví dụ về Python để xóa một hàng khỏi bảng MySQL

Thực hiện theo các bước sau. –

Cách xóa một hàng trong MySQL bằng Python

  1. Kết nối với MySQL từ Python

    Tham khảo kết nối cơ sở dữ liệu MySQL trên Python để kết nối với cơ sở dữ liệu MySQL từ Python bằng mô-đun MySQL Connector

  2. Xác định truy vấn xóa SQL

    Tiếp theo, chuẩn bị truy vấn xóa SQL để xóa một hàng khỏi bảng. Truy vấn xóa chứa hàng sẽ bị xóa dựa trên một điều kiện được đặt trong mệnh đề where của truy vấn.
    Ví dụ:

    Displaying laptop record Before Deleting it
    [7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]
    
    Record Deleted successfully 
    MySQL connection is closed
    2

  3. Nhận đối tượng con trỏ từ kết nối

    Tiếp theo, sử dụng phương thức

    Displaying laptop record Before Deleting it
    [7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]
    
    Record Deleted successfully 
    MySQL connection is closed
    3 để tạo đối tượng con trỏ. Phương thức này tạo một đối tượng
    Displaying laptop record Before Deleting it
    [7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]
    
    Record Deleted successfully 
    MySQL connection is closed
    4 mới

  4. Thực hiện truy vấn xóa bằng phương thức exec[]

    Thực hiện truy vấn xóa bằng phương thức

    Displaying laptop record Before Deleting it
    [7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]
    
    Record Deleted successfully 
    MySQL connection is closed
    5. Phương thức này thực thi thao tác được lưu trữ trong truy vấn xóa.
    Sau thao tác xóa thành công, phương thức
    Displaying laptop record Before Deleting it
    [7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]
    
    Record Deleted successfully 
    MySQL connection is closed
    6 trả về cho chúng ta số hàng bị ảnh hưởng.

  5. Cam kết thay đổi của bạn

    Sau khi thực hiện thành công thao tác xóa, hãy thực hiện các thay đổi liên tục vào cơ sở dữ liệu bằng cách sử dụng

    Displaying laptop record Before Deleting it
    [7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]
    
    Record Deleted successfully 
    MySQL connection is closed
    7 của lớp kết nối

  6. Nhận số hàng bị ảnh hưởng

    Sử dụng phương pháp

    Displaying laptop record Before Deleting it
    [7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]
    
    Record Deleted successfully 
    MySQL connection is closed
    8 để lấy số lượng hàng bị ảnh hưởng. Số lượng phụ thuộc vào số lượng hàng bạn đang xóa.
    Bạn cũng có thể Thực hiện truy vấn chọn MySQL từ Python để Xác minh kết quả.

  7. Đóng đối tượng con trỏ và đối tượng kết nối cơ sở dữ liệu

    sử dụng phương pháp

    Displaying laptop record Before Deleting it
    [7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]
    
    Record Deleted successfully 
    MySQL connection is closed
    9 và
    import mysql.connector
    
    try:
        connection = mysql.connector.connect[host='localhost',
                                             database='electronics',
                                             user='pynative',
                                             password='pynative@#29']
        cursor = connection.cursor[]
        sql_Delete_query = """Delete from Laptop where id = %s"""
        # row to delete
        laptopId = 6
        cursor.execute[sql_Delete_query, [laptopId,]]
        connection.commit[]
        print["Record Deleted successfully "]
    
    except mysql.connector.Error as error:
        print["Failed to Delete record from table: {}".format[error]]
    finally:
        if connection.is_connected[]:
            cursor.close[]
            connection.close[]
            print["MySQL connection is closed"]
    0 để đóng các kết nối đang mở sau khi công việc của bạn hoàn thành

python xóa dữ liệu khỏi bảng MySQL

Ví dụ

import mysql.connector

try:
    connection = mysql.connector.connect[host='localhost',
                                         database='electronics',
                                         user='root']
    cursor = connection.cursor[]
    print["Laptop table before deleting a row"]
    sql_select_query = """select * from Laptop where id = 7"""
    cursor.execute[sql_select_query]
    record = cursor.fetchone[]
    print[record]

    # Delete a record
    sql_Delete_query = """Delete from Laptop where id = 7"""
    cursor.execute[sql_Delete_query]
    connection.commit[]
    print['number of rows deleted', cursor.rowcount]

    # Verify using select query [optional]
    cursor.execute[sql_select_query]
    records = cursor.fetchall[]
    if len[records] == 0:
        print["Record Deleted successfully "]

except mysql.connector.Error as error:
    print["Failed to delete record from table: {}".format[error]]
finally:
    if connection.is_connected[]:
        cursor.close[]
        connection.close[]
        print["MySQL connection is closed"]

đầu ra

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed

Bảng máy tính xách tay MySQL sau khi xóa bản ghi

Sử dụng Biến Python trong truy vấn SQL để xóa dữ liệu khỏi bảng

Đôi khi, chúng tôi cần đầu vào từ người dùng, chẳng hạn như khi người dùng xóa dữ liệu của họ khỏi cổng web hoặc bất kỳ chi tiết nào khác thông qua Giao diện người dùng. trong trường hợp như vậy, cách tốt nhất là sử dụng truy vấn được tham số hóa

Câu lệnh đã chuẩn bị sẵn hoặc truy vấn được tham số hóa sử dụng trình giữ chỗ [

import mysql.connector

try:
    connection = mysql.connector.connect[host='localhost',
                                         database='electronics',
                                         user='pynative',
                                         password='pynative@#29']
    cursor = connection.cursor[]
    sql_Delete_query = """Delete from Laptop where id = %s"""
    # row to delete
    laptopId = 6
    cursor.execute[sql_Delete_query, [laptopId,]]
    connection.commit[]
    print["Record Deleted successfully "]

except mysql.connector.Error as error:
    print["Failed to Delete record from table: {}".format[error]]
finally:
    if connection.is_connected[]:
        cursor.close[]
        connection.close[]
        print["MySQL connection is closed"]
1 ] bên trong bất kỳ câu lệnh SQL nào có chứa đầu vào từ người dùng. tôi. e. , Sử dụng truy vấn được tham số hóa, chúng ta có thể chuyển các biến Python dưới dạng tham số truy vấn trong đó trình giữ chỗ [
import mysql.connector

try:
    connection = mysql.connector.connect[host='localhost',
                                         database='electronics',
                                         user='pynative',
                                         password='pynative@#29']
    cursor = connection.cursor[]
    sql_Delete_query = """Delete from Laptop where id = %s"""
    # row to delete
    laptopId = 6
    cursor.execute[sql_Delete_query, [laptopId,]]
    connection.commit[]
    print["Record Deleted successfully "]

except mysql.connector.Error as error:
    print["Failed to Delete record from table: {}".format[error]]
finally:
    if connection.is_connected[]:
        cursor.close[]
        connection.close[]
        print["MySQL connection is closed"]
1] được sử dụng cho tham số

________số 8

đầu ra

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed
4

Ghi chú. Chúng tôi đã xác định truy vấn xóa SQL với trình giữ chỗ chứa Id máy tính xách tay để xóa ở định dạng tuple. Tham khảo Chọn truy vấn để tìm nạp dữ liệu từ bảng MySQL để xác minh kết quả thao tác xóa của bạn

Python Xóa nhiều hàng khỏi bảng MySQL

Đôi khi chúng ta cần xóa N-số hàng phù hợp với một điều kiện cụ thể. Ví dụ: bạn muốn xóa dữ liệu nhân viên khỏi bảng nhân viên đã rời khỏi tổ chức. Bạn có thể xóa nhiều hàng khỏi bảng MySQL bằng một lần xóa Truy vấn SQL trong Python

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed
5

đầu ra

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed
6

Bảng máy tính xách tay MySQL sau khi xóa nhiều bản ghi

Tham khảo Chọn truy vấn để tìm nạp dữ liệu từ bảng MySQL để xác minh kết quả thao tác xóa của bạn

Hãy hiểu chương trình trên. –

  • Chúng tôi đã xác định truy vấn xóa SQL với trình giữ chỗ chứa ID máy tính xách tay để xóa ở định dạng danh sách. Danh sách này chứa một bộ cho mỗi hàng. Ở đây chúng tôi đã tạo hai bộ dữ liệu, vì vậy chúng tôi đang xóa hai hàng
  • Tiếp theo, chúng tôi đã sử dụng phương thức
    import mysql.connector
    
    try:
        connection = mysql.connector.connect[host='localhost',
                                             database='electronics',
                                             user='pynative',
                                             password='pynative@#29']
        cursor = connection.cursor[]
        sql_Delete_query = """Delete from Laptop where id = %s"""
        # row to delete
        laptopId = 6
        cursor.execute[sql_Delete_query, [laptopId,]]
        connection.commit[]
        print["Record Deleted successfully "]
    
    except mysql.connector.Error as error:
        print["Failed to Delete record from table: {}".format[error]]
    finally:
        if connection.is_connected[]:
            cursor.close[]
            connection.close[]
            print["MySQL connection is closed"]
    3 của con trỏ để xóa nhiều hàng của bảng cơ sở dữ liệu. Sử dụng phương pháp
    Displaying laptop record Before Deleting it
    [7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]
    
    Record Deleted successfully 
    MySQL connection is closed
    8, chúng tôi có thể tìm thấy có bao nhiêu hàng đã được xóa thành công

Xóa tất cả các hàng khỏi bảng trong Python

Có thể xóa tất cả các hàng khỏi bảng cơ sở dữ liệu MySQL bằng truy vấn SQL cắt bớt. Rút ngắn các truy vấn SQL xóa tất cả dữ liệu khỏi bảng, thường bỏ qua số lượng cơ chế thực thi tính toàn vẹn

Bạn có thể tham khảo bài viết trên Wikipedia để đọc thêm về SQL truncate. Hãy chuyển sang mã python để xóa tất cả các hàng khỏi bảng MySQL

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed
9

đầu ra

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed
0

Xóa bảng và cơ sở dữ liệu MySQL khỏi Python

Bạn có thể xóa các bảng cũ, không sử dụng và cơ sở dữ liệu tạm thời và các bảng bằng cách sử dụng câu lệnh DROP TABLE và DROP DATABASE. Hãy xem bản demo

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed
1

đầu ra

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed
2

Xóa cột Bảng MySQL khỏi Python

Sử dụng lệnh thay đổi cột thả bảng để xóa một cột khỏi bảng MySQL

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed
0

đầu ra

Displaying laptop record Before Deleting it
[7, 'Acer Predator Triton', 2435.0, datetime.date[2019, 8, 17]]

Record Deleted successfully 
MySQL connection is closed
1

Bước tiếp theo

Để thực hành những gì bạn đã học trong bài viết này, vui lòng giải một dự án Bài tập về cơ sở dữ liệu Python để thực hành và thành thạo các thao tác với Cơ sở dữ liệu Python

Làm cách nào để xóa văn bản trong Python?

Python Xóa ký tự khỏi chuỗi – Cách xóa ký tự khỏi chuỗi. Trong Python, bạn có thể sử dụng các phương thức replace[] và translate[] để chỉ định ký tự nào bạn muốn xóa khỏi chuỗi và trả về kết quả chuỗi mới đã sửa đổi .

Có lệnh xóa trong Python không?

Từ khóa del dùng để xóa đối tượng . Trong Python, mọi thứ đều là một đối tượng, do đó, từ khóa del cũng có thể được sử dụng để xóa các biến, danh sách hoặc một phần của danh sách, v.v.

Chủ Đề