Site icon DataFlair

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:

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:

User Input:

Select Query Execution:

User Confirmation:

Deletion Execution:

Error Handling:

Connection Closure:

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:

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

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.

Exit mobile version