How to Delete Record from Database using PDBC

Python course with 57 real-time projects - Learn Python

In the practical landscape of Python database interaction, we shift our focus to a fundamental task—deleting records from a database using Python Database Connection (PDBC). This skill is indispensable for developers managing databases within their applications, providing a means to efficiently remove specific data entries and maintain the integrity of their databases.

As we delve into this topic, developers will gain a comprehensive understanding of the process, empowering them to interact dynamically with their databases and manage data effectively. In mastering this skill, developers gain the ability to streamline their database management tasks and ensure data integrity across their applications.

Topic Explanation:

This exploration unfolds in two parts, unraveling the intricacies of deleting records from a database using Python’s Database Connection. Firstly, we will establish a connection to the database, facilitated by PDBC, a vital prerequisite for any database-related task. Once connected, we’ll delve into crafting SQL queries to selectively delete records based on user-defined criteria.

Navigating through the code, we’ll illustrate the step-by-step process of sending deletion requests to the database and ensuring the seamless removal of specified records. This hands-on guide not only imparts technical proficiency but also equips developers with the skills to enhance the efficiency and manageability of their applications.

In the second part of our exploration, we will focus on handling potential challenges and ensuring the secure deletion of records. This involves incorporating error-handling mechanisms to address situations where a record might not exist or if there are constraints affecting the deletion process.

By navigating through practical examples, developers will grasp how to implement robust solutions, making their applications more resilient and user-friendly. This aspect adds a layer of depth to the exploration, emphasizing not just the technical know-how but also the importance of creating reliable and error-tolerant database operations.

Prerequisites:

  • Basic understanding of Python programming.
  • Installation of the MySQL database.
  • Familiarity with database concepts (tables, records, SQL queries).
  • Python Database Connection (PDBC) library installed (e.g., MySQLdb).

Code With Comments:

# Importing the MySQLdb library for MySQL database connection
import MySQLdb

try:
    # Establishing a connection to the MySQL database
    con = MySQLdb.Connect(host="localhost", user="root", password="root", database="dataflair")
    print("Connection success")

    # Taking user input for the employee id to be deleted
    empid = int(input("Enter employee id for delete: "))

    # Query to select and display the record with the given employee id
    sql = "select * from employee where eid=%d"
    cur = con.cursor()
    cur.execute(sql % empid)
    result = cur.fetchone()

    # Checking if the record with the given id exists
    if cur.rowcount == 0:
        print("--------NO RECORD FOUND-----------------")
    else:
        # Displaying the details of the record for confirmation
        print("ID      NAME   DEPARTMENT   SALARY")
        print("%d      %s       %s      %d" % (result[0], result[1], result[2], result[3]))

        # Taking user confirmation for deletion
        m = input("Are You sure want to delete(yes/no):")

        # If user confirms, executing the delete query
        if m == 'yes':
            sql = "delete from employee where eid=%d"
            cur = con.cursor()
            cur.execute(sql % empid)
            con.commit()
            print("Record Deleted...........")

except Exception as msg:
    # Handling exceptions and printing error messages
    print(msg)
finally:
    # Closing the database connection
    con.close()
    print("Connection close")

Output:

The program displays the details of the specified record for user confirmation.
If the user confirms deletion, it prints “Record Deleted………..”
The connection success and close messages indicate the successful execution of the program.

Code Explanation:

Connection Establishment:

  • The program uses the `MySQLdb` library to establish a connection to the MySQL database.
  • `MySQLdb.Connect()` is used to provide connection details such as host, user, password, and database.

User Input:

  • The user is prompted to enter the employee id for the record they want to delete.
  • The input is converted to an integer using `int(input())`.

Select Query Execution:

  • A SQL query is executed to select and fetch the details of the specified employee id from the database.
  • `cur.execute(sql % empid)` executes the query, and `cur.fetchone()` fetches the result.

User Confirmation:

  • If the record exists, the program asks the user for confirmation before proceeding with the deletion.
  • -The user’s response is stored in the variable `m`.

Deletion Execution:

  • – If the user confirms with “yes,” a delete query is executed to remove the specified record.
  • – `cur.execute(sql % empid)` performs the deletion, and `con.commit()` commits the changes.

Error Handling:

  • The program includes a try-except block to handle exceptions that may occur during execution.
  • Any exception message is printed to provide information about the error.

Connection Closure:

  • In the `finally` block, the database connection is closed using `con.close()`.

This code allows users to input an employee id, fetches the corresponding record, asks for confirmation, and deletes the record if confirmed, with appropriate error handling.

Conclusion:

In concluding our exploration into Python’s practical database interaction, we’ve delved into the essential skill of deleting records using Python Database Connection (PDBC). This proficiency serves as a crucial tool for developers, allowing them to streamline their databases by efficiently removing specific data entries.

As developers master this skill, they not only enhance their ability to manage data effectively but also ensure the integrity and efficiency of their applications. Through this hands-on experience, developers acquire a versatile toolset, equipping them to navigate the dynamic landscape of database management in Python.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *