CRUD operations in Oracle Database using Python
In my previous post, I explained how to connect to Oracle Database using Python. In this blog series, I will explain how to perform CRUD Operations using Python.
This is the first blog of the series, where I explain the basics of the cx_Oracle module.
I'll use the emp_test table for all the examples in this series. Create the table using the below script.
CREATE TABLE EMP_TEST(EMPNO NUMBER(4,0) PRIMARY KEY,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4,0),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2,0));
To perform any action with the database, basically, we need to perform three basic steps.:
- First, we need to import the cx_Oracle module. cx_Oracle module provides the API for accessing the Oracle Database. There are different modules available to connect with different databases.
- import cx_Oracle
- Second, we need to establish the database connection. cx_Oracle module provides connect method for the database connection. We need to pass username, password, and database connection string as parameters.
- conn = cx_Oracle.connect('username','password','db_connect_string')
- In the last, we need to create a cursor object. Create cursor object to execute queries and get results after execution.
- cur = conn.cursor()
We need to perform these three steps each time no matter which database we are using.
After establishing the connection with the database, we need to execute the various SQL statements. For that the cursor object provides different methods as follow:
- Methods to execute SQL statement:
- cursor.execute() : Used to execute a single query
- cursor.executeall() : Used to execute parameterised query
Similarly, the cursor object also provides three methods to fetch the result set of a SQL query from the database.
- Methods to fetch the result:
- cursor.fetchone() : Used to fetch only one row
- cursor.fetchall() : Used fetch all rows
- cursor.fetchmany(n) : Used to fetch n number of rows
Once we completed these operations, we can either commit the connection or roll back the connection. We can do this using the below methods of the connection object.
- Commit or Rollback:
- connection.commit()
- connection.rollback()
And after all these steps, we need to close the cursor and connection using the below methods
- cursor.close() : Used to close the cursor
- connection.close() : Used to close the connection
Now we understood the basic steps to connect with the Oracle database and the available methods to execute the statements and fetch the records from the database. In the next post, I'll explain 'C' of the CRUD operation, that is how to create records into the Oracle database.
Comments
Post a Comment