Oracle Database Connection in Python

Python Methods and Functions

Oracle Database
To link any database with our Python program, we needed some kind of connector, which is nothing other than module cx_Oracle .

To install cx_Oracle:

 pip install cx_Oracle 

With this command you can install the cx_Oracle package , but first you need to install the Oracle database on your PC.

How to use this module to connect

  • Import a specific module database
    Ex. import cx_Oracle
  • connect (): now connect the Python program to the Oracle database using the connect () function.
     con = cx_Oracle.connect ('username / password @ localhost') 
  • cursor (): to execute the sql query and provide the result, some special object is required — nothing but cursor () object
     cursor = cx_Oracle.cursor () 
  • execute method:

    cursor.execute (sqlquery) - - - - & gt; to execute single query.
    cursor.execute (sqlqueries) - - - - & gt; to execute a group of multiple sqlquery seperated by “;”

  • commit (): For a DML (Data Manuplate Language) query in this query, you have an operation (update, insert, delete), we need commit (), then only the result is reflected in the database.
  • Fetch (): fetches the next row from the query result set and returns one sequence, or None if there are no more rows available.
  • close (): after all submenus are done to close all operations
     cursor.close () con.close () 

Creting table:

# import module

import cx_Oracle 

 

 
# Create table in Oracle database

try :

 

con = cx_Oracle.connect ( 'scott / tiger @ localhost' )

 

  # Now run sqlquery

cursor = con.cursor ()

 

# Creates a table in a roll with the title number

cursor.execute ("create table student (srollno number,

name varchar2 ( 10 ), efees number ( 10 , 2 ) ")

  

print ( "Table Created successful" )

 

except cx_Oracle.DatabaseError as e:

  print ( " There is a problem with Oracle " , e)

 
# finally writing if any error occurs
# then we can also close all database operations

finally :

if cursor:

  cursor.close ()

if con:

con.close ()

Exit :

 Table Created successful 

Insert into table:

# Program for creating a table in the Oracle database

import cx_Oracle

  

try :

 

con = cx_Oracle.connect ( 'scott / tiger @ localhost' )

  

  # Now run sqlquery

cursor = con.cursor ()

cursor.execute ( "insert into student values ​​(19585, Niranjan Shukla, 72000" )

 

# the commit that inserts the supplied data

  con.commit ()

 

print ( "value inserted successful" )

 

except cx_Oracle.DatabaseError as e:

print ( "There is a problem with Oracle" , e)

  
# finally writing if any error occurs
# then we can also close everything database operations

finally < / code> :

if cursor:

cursor.close ()

if con:

con.close ()

Exit :

 value inserted successful 




Get Solution for free from DataCamp guru