How to Auto Generate Code in Python OOPS with PDBC

Python course with 57 real-time projects - Learn Python

In the realm of Python programming, our attention now converges on a crucial aspect—auto-generating code within Object-Oriented Programming (OOPS) frameworks, coupled with Python Database Connection Part-2 (PDBC). This topic bridges the gap between efficient code generation and seamless database interaction, offering developers a streamlined approach to handling data-driven applications.

Through this exploration, developers will delve into the intricacies of auto-generating code within OOPS paradigms, enhancing their productivity and codebase maintainability.

Topic Explanation:

In this dual-part exploration, we embark on a journey to uncover the nuances of auto-generating code in Python’s OOPS framework, complemented by Python Database Connection Part-2 (PDBC). Firstly, we’ll delve into the principles of OOPS, understanding how classes, objects, and inheritance can be leveraged to automate code generation tasks.

Next, we’ll integrate PDBC to seamlessly interact with databases, enabling the auto-generation of code that fetches, modifies, or deletes database records. This holistic approach empowers developers to create robust, data-driven applications with minimal manual intervention.

Through hands-on examples and practical exercises, developers will gain insights into implementing auto-generated code patterns within real-world applications. They will learn how to design modular and extensible code structures that facilitate easy maintenance and scalability, reducing the burden of manual coding and enhancing overall development productivity.

By mastering the art of auto-generating code with Python OOPS and PDBC, developers can elevate their programming skills and build sophisticated, data-driven applications with ease and efficiency.

Prerequisites:

  • Proficiency in Python programming language
  • Understanding of Object-Oriented Programming (OOPS) concepts
  • Familiarity with Python Database Connection (PDBC) fundamentals

Code With Comments:

import MySQLdb
#Importing the MySQLdb module for establishing a connection to the MySQL database.

class MyDataBase:
#Defining a class named `MyDataBase` to encapsulate methods related to database operations.

    def __init__(self):        self.con=MySQLdb.Connect(host="localhost",user="root",password="root",database="dataflair")
        print("Connection success")
#Initializing the class with the constructor method `__init__()` to establish a connection to the MySQL database.




    def autoId(self):
#Defining a method `autoId()` to automatically generate an ID for the new record to be inserted into the database.

        sql="select max(eid) from employee"
        self.cur=self.con.cursor()
        self.cur.execute(sql)
        result=self.cur.fetchone()
        self.maxid=result[0]
        self.maxid=id=self.maxid+1
#Executing a SQL query to fetch the maximum employee ID from the database and auto-incrementing it by one for the new record.


    def insertData(self,empname,empdept,empsal):
#Defining a method `insertData()` to insert a new record into the database.

        self.autoId()
#Calling the `autoId()` method to generate a unique ID for the new record.
     
   self.cur=self.con.cursor()
#Creating a cursor object to execute SQL queries.

        self.cur.execute(sql % value)
#Executing an SQL insert query to add the new record to the database.




        print("record inserted: ",self.cur.rowcount)
        self.con.commit()
#Printing a confirmation message and committing the transaction to save changes to the database.

    def searchAll(self):
#Defining a method `searchAll()` to retrieve all records from the database.

        sql="select * from employee"
#Preparing an SQL query to select all records from the 'employee' table.

        for row in result:
            print("---------------------------------------------")
            print("%d        %s       %s        %d"%(row[0],row[1],row[2],row[3]))

#Printing each retrieved record in a formatted manner.

    def deleteById(self,empid):
#Defining a method `deleteById()` to delete a record from the database based on the provided ID.

        self.cur.execute(sql % empid)
#Executing an SQL query to fetch the record with the specified ID from the database.
            
if(choice=='yes'):
                sql="delete from employee where eid=%d"

#Checking user confirmation and executing an SQL delete query to remove the record from the database.

    def __del__(self):
        print("Connection close")
        self.con.close()

Defining the destructor method `__del__()` to close the database connection when the object is deleted.

ch=0
M1=MyDataBase()
#Creating an instance of the `MyDataBase` class to interact with the database.

    if(ch==1):
        ename = input("Enter Employee Name:")
        edept=input("Enter Employee Department:")
        esal = int(input("Enter Employee Salary:"))
        M1.insertData(ename,edept,esal)
#Inserting a new record into the database based on user input.

    elif(ch==2):
        eid = int(input("Enter Employee Id for Search:"))
        M1.searchById(eid)
#Searching for a record in the database based on the provided ID.

    elif(ch==3):
        M1.searchAll()
#Retrieving all records from the database and displaying them.


    elif(ch==4):
        eid = int(input("Enter Employee Id for Delete:"))
        M1.deleteById(eid)
#Deleting a record from the database based on the provided ID.

# eid = int(input("Enter Employee Id for Delete:"))
# M1.deleteById(eid)
#M1.searchById(eid)


Sample code for individual method calls.


#M1.searchAll()
# M1.autoId()
# print(" Employee ID:",M1.maxid)
# ename=input("Enter Employee Name:")
# edept=input("Enter Employee Department:")
# esal = int(input("Enter Employee Salary:"))
# M1.insertData(ename,edept,esal)

Additional sample code for individual method calls.
    if(ch==5):
        break


Exiting the loop if the user chooses the exit option.
# M1=MyDataBase()


Sample code for creating a new instance of the `MyDataBase` class.
# eid = int(input("Enter Employee Id for Delete:"))
# M1.deleteById(eid)
#M1.searchById(eid)

Sample code for calling specific methods.

#M1.searchAll()
# M1.autoId()
# print(" Employee ID:",M1.maxid)
# ename=input("Enter Employee Name:")
# edept=input("Enter Employee Department

Output:
The code provided does not execute directly within this environment as it requires access to a MySQL database and user input. However, I can simulate the expected output based on the logic and flow of the code:

Connection success
—————Database Menu—————-
1.Insert Record
2.Search Record By Id
3.Search All Record
4.Delete Record By Id
5.Exit
———————————————
Enter your Choice1
Enter Employee Name: John
Enter Employee Department: HR
Enter Employee Salary: 5000
record inserted: 1
Connection close

Code Explanation:

  • Importing MySQLdb Module:

The `MySQLdb` module is imported to enable interaction with MySQL databases.

  • Class Definition – MyDataBase:

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

A class named `MyDataBase` is defined to encapsulate methods for interacting with the database.

  • Constructor Method – \_\_init\_\_():

Initializes the class instance and establishes a connection to the MySQL database using the provided credentials.

  • autoId() Method:

Automatically generates an ID for the new record to be inserted into the database by fetching the maximum ID from the ’employee’ table and incrementing it by one.

  • insertData() Method:

Inserts a new record into the ’employee’ table with the provided employee details, including name, department, and salary. It utilizes the `autoId()` method to generate a unique ID for the new record.

  • searchAll() Method:

Retrieves all records from the ’employee’ table and displays them in a formatted manner.

  • deleteById() Method:

Deletes a record from the ’employee’ table based on the provided employee ID. It first checks if the record exists and prompts the user for confirmation before deletion.

  • Destructor Method – \_\_del\_\_():

Closes the database connection when the object is deleted or goes out of scope.

  • Database Menu Loop:

Creates an instance of the `MyDataBase` class and displays a menu for database operations. Based on the user’s choice, it calls the respective methods to perform insert, search, or delete operations on the database.

Conclusion:

Wrapping up this expedition into Python’s practical domain, we uncover the dynamic synergy between auto-generating code in Object-Oriented Programming (OOPS) and Python Database Connection Part-2 (PDBC). This fusion presents developers with a potent arsenal to streamline database interactions and bolster application efficiency.

Through mastery of auto-generated code within OOPS frameworks, developers not only boost productivity but also ensure the resilience and scalability of their data-driven applications.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

Leave a Reply

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