To connect Oracle Autonomous Database from Python, we require below components
- Oracle Instant Client
- cx_Oracle Python library
- A valid wallet for an ADB service
- Python environment.
Oracle Instant Client
Oracle Instant Client libraries are required to connect to Oracle Database from any client OS. These are not Python-specific libraries. Using these libraries, you can connect to Oracle Database from the programs written in any other programming language.
Download the Oracle Instant Client from here.
I selected Instant Client for Microsoft Windows (x64). It will redirect to the download page where two packages are available to download. Basic Package and Basic Light Package. Download any one package and unzip the downloaded package into a suitable location.
Note that Windows 7 is not supported. Also, both the Basic Package and Basic Light Package require Microsoft Visual Studio 2017 Redistributable.
Add the location of the instant client to the Path Environment Variable. This is required so that the cx_Oracle module can access the instant client libraries.
cx_Oracle Python library
cx_Oracle is a Python module that enables access to Oracle Database. Python 3.5 and higher versions and Oracle 11.2, 12, 18, 19, and 21 client libraries are supported by cx_Oracle 8. For more detail check
this.
Install cx_Oracle using pip :
pip install cx_Oracle
Oracle ADB Wallet
The final component we require is the wallet containing the credentials and connect string details to connect to Oracle Autonomous Database.
To download the wallet, log in to the OCI console and go to the database instance. Then click on the DB Connection and a popup will open to download the wallet.
Unzip the downloaded wallet and copy all the files into the below path of your Oracle Instant Client. If this directory is not present then create it and then copy all the files into it.
OracleInstantClient_Home\network\admin
All the setup is ready and it's time to write some code to connect to the database.
import cx_Oracle
username = '######'
password = '########'
connect_string = 'dbrutvik_medium'
con = cx_Oracle.connect(username,password,connect_string)
cur = con.cursor()
stmt = 'SELECT SYSDATE FROM DUAL'
cur.execute(stmt)
res = cur.fetchall()
print(res)
print(' ')
cur.close()
Output:
[(datetime.datetime(2021, 4, 25, 9, 36, 8),)]
And that's it. Connection to Oracle Automonus Database from Python is really very simple.
Comments
Post a Comment