Oracle Database - Connect to Oracle database using Python
by
Jeremy Canfield |
Updated: February 11 2024
| Oracle Database articles
The oracledb module can be used to connect to an Oracle database. pip install can be used to install the oracledb module.
pip install oracledb
And here is an example of how to connect to Oracle database.
#!/usr/bin/python3
import oracledb
import sys
try:
connection = oracledb.connect(user="johndoe", password="itsasecret", dsn="10.11.12.13:1521/abc123")
except Exception as exception:
print(f"got the following exception when attempting to connect: {exception}")
sys.exit()
else:
print("Successfully connected to Oracle Database")
try:
connection.close()
except Exception as exception:
print(f"got the following exception when attempting connection.close(): {exception}")
else:
print("Successfully disconnected from Oracle Database")
Taking this a step further, here is how you could perform a SELECT statement.
#!/usr/bin/python3
import oracledb
import sys
user = "johndoe"
dsn = "10.11.12.13:1521/abc123"
try:
connection = oracledb.connect(user="johndoe", password="itsasecret", dsn="10.11.12.13:1521/abc123")
except Exception as exception:
print(f"got the following exception when attempting to connect to {dsn} as {user}: {exception}")
sys.exit()
else:
print(f"Successfully connected to Oracle Database {dsn} as {user}")
try:
cursor = connection.cursor()
except Exception as exception:
print(f"got the following exception when attempting connection.cursor(): {exception}")
else:
print(f"connection.cursor() appears to have been successful")
query = "SELECT * FROM orders"
try:
for row in cursor.execute(query):
date_updated = row[0]
order_status = row[1]
print(f"date_updated = {date_updated}")
print(f"order_status = {order_status}")
except Exception as exception:
print(f"got the following exception when attempting {query}: {exception}")
try:
connection.close()
except Exception as exception:
print(f"got the following exception when attempting connection.close(): {exception}")
else:
print("Successfully disconnected from Oracle Database")
Did you find this article helpful?
If so, consider buying me a coffee over at