Here I am giving some examples of Python programs to connect to Oracle Database using cx_Oracle package.
1. Connect to Oracle Database in Python and Print The Version Number
In the following example, it will import the package cx_Oracle in Python program and then will make the connection to Oracle database and will get the database version.
import cx_Oracle # scott is the username and tiger is the password. Change below according to your username and password. # also change the localhost with your host and orcl to your database SID con = cx_Oracle.connect("scott", "tiger", "localhost/orcl") print(con.version) con.close
2. Print The Oracle SQL Query Result
Example to connect to Oracle database, perform a SQL query and print the results.
import cx_Oracle con = cx_Oracle.connect("scott", "tiger", "localhost/orcl") cur = con.cursor() cur.execute('select * from dept order by deptno') for result in cur: print (result) cur.close() con.close()
(10, 'ACCOUNTING', 'NEW YORK') (20, 'RESEARCH', 'DALLAS') (30, 'SALES', 'CHICAGO') (40, 'OPERATIONS', 'BOSTON')
3. Example to Update Records in Oracle Database Table and Commit
It will update the records in the EMP table of SCOTT schema and then will print the affected rows by the update and then performs a commit.
import cx_Oracle con = cx_Oracle.connect("scott", "tiger", "localhost/orcl") cur = con.cursor() cur.execute("Update emp2 set comm = 80 where deptno = 20") print ("Rows affected: ", cur.rowcount) cur.close() con.commit() con.close()
Rows affected: 4