Press "Enter" to skip to content

Python – Connect to Oracle Database

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

Output

11.2.0.1.0

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()

Output

(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()

Output

Rows affected: 4

See also:

Have you found the answer to your question? If not, you can discuss it with me in the comments section below or join my Q&A community OrclQA.com for developers and ask your question. It is FREE.

Vinish Kapoor

Follow

Hi, I am a full stack developer and writing about development. I document everything I learn and help thousands of people. foxinfotech.in is created, written, and maintained by me; it is built on WordPress, and hosted by Bluehost. Connect with me on Facebook, Twitter, GitHub, and get notifications for new posts.

guest
0 Comments
Inline Feedbacks
View all comments