Skip to content

Description:

  • Work with data in OracleDB

Resources:

Notes:

  • These examples use python-oracledb in Thin mode, which connects directly to Oracle Database without Oracle Client libraries.
  • python-oracledb is the successor to the cx_Oracle driver.

Source and license:

This notebook reads its settings from environment variables. Set them before starting Jupyter:

  • ORACLE_HOST: hostname of your Oracle Database
  • ORACLE_PORT: optional, defaults to 1521
  • ORACLE_USER: database user name
  • ORACLE_PASSWORD: password for that user
  • ORACLE_SERVICE_NAME: service name of the database (for example FREEPDB1)

Connect to a remote oracle database in Thin Mode using oracledb, insert a table and data, and read data from the table

import json
import os
import platform
# import getpass
import oracledb
# userpwd = getpass.getpass("Enter password: ")
userpwd = os.environ["ORACLE_PASSWORD"]
# Create an example Building Object we'll use in our Oracle Database
class Building(object):
def __init__(self, building_id, description, num_floors):
self.building_id = building_id
self.description = description
self.num_floors = num_floors
def __repr__(self):
return "<Building %s: %s>" % (self.building_id, self.description)
def __eq__(self, other):
if isinstance(other, Building):
return other.building_id == self.building_id \
and other.description == self.description \
and other.num_floors == self.num_floors
return NotImplemented
def to_json(self):
return json.dumps(self.__dict__)
@classmethod
def from_json(cls, value):
result = json.loads(value)
return cls(**result)
# Convert a Python building object to SQL JSON type that can be read as a string
def building_in_converter(value):
return value.to_json()
def input_type_handler(cursor, value, num_elements):
if isinstance(value, Building):
return cursor.var(oracledb.STRING, arraysize=num_elements,
inconverter=building_in_converter)
# Instantiate a Building object
building = Building(1, "The First Building", 5) # Python object
# Connect to the Oracle DB, create a table, insert data into the table, and query data from the table
with oracledb.connect(
user=os.environ["ORACLE_USER"],
password=userpwd,
host=os.environ["ORACLE_HOST"],
port=int(os.environ.get("ORACLE_PORT", "1521")),
service_name=os.environ["ORACLE_SERVICE_NAME"],
) as conn:
print("Connected to the db")
with conn.cursor() as cur:
cur.execute(
"""create table BuildingTable (
ID number(9) not null,
BuildingDetails varchar2(400),
constraint TestTempTable_pk primary key (ID))"""
)
cur.execute("truncate table BuildingTable")
cur.inputtypehandler = input_type_handler
cur.execute("insert into BuildingTable (ID, BuildingDetails) values (:1, :2)",
(building.building_id, building))
conn.commit()
print("Querying the row just inserted...")
cur.execute("select ID, BuildingDetails from BuildingTable")
for (int_col, string_col) in cur:
print("Building ID:", int_col)
print("Building Details in JSON format:", string_col)

ganymede is made by Eugo