This topic describes how to connect to and use OceanBase Database in Oracle-compatible mode by using the Python cx_Oracle driver. The OceanBase Database client installation package includes a compatible cx_Oracle driver. Use the cx_Oracle driver provided by OceanBase Database, which is located in the /u01/obclient/python/ directory. Do not install the official Oracle version by using the pip install cx_Oracle command, as this may cause compatibility issues.
Prerequisites
- You have installed Python 3.7 or later.
- You have installed OceanBase Database and created a tenant in Oracle-compatible mode.
- You have installed the libobclient and OBCI components.
Procedure
To connect to OceanBase Database in Oracle-compatible mode by using the cx_Oracle driver, perform the following steps:
Step 1: Install the Python 3.7 environment
Ensure that Python 3.7 or later is installed on your system. You can check the Python version by using the following command:
python3 --version
If it is not installed, install Python 3.7 according to your operating system.
Step 2: Install the libobclient and OBCI components
Install the OceanBase client components, including libobclient and OBCI:
# Uninstall the earlier version (if any).
rpm -e libobclient
rpm -e obci
# Install the new version
rpm -ivh libobclient-2.2.11-42025062010.el7.x86_64.rpm
rpm -ivh obci-2.1.1-342025070917.el7.x86_64.rpm
Notice
Ensure that the libobclient version is greater than or equal to 2.2.11 and the obci version is greater than or equal to 2.1.1. Earlier versions may cause connection failures or functional abnormalities.
Step 3: Install the cx_Oracle driver
After installing libobclient and OBCI, the cx_Oracle driver package provided by OceanBase Database is located in the /u01/obclient/python/ directory. Copy the driver package to the target directory, extract it, and install it:
# Create the target installation directory.
mkdir -p /directory/of/
# Copy the cx_Oracle driver package provided by OceanBase Database.
cp /u01/obclient/python/cx_Oracle-8.3.0.tar.gz /directory/of/
# Switch to the installation directory.
cd /directory/of/
# Extract the cx_Oracle driver package.
tar -xzf cx_Oracle-8.3.0.tar.gz
# Navigate to the directory after decompression
cd cx_Oracle-8.3.0
# Install the cx_Oracle driver
python3 setup.py install
After the installation is complete, the system generates the cx_Oracle module in the /usr/local/lib/python3.7/site-packages/ directory.
Step 4: Configure environment variables
Set the LD_LIBRARY_PATH environment variable to ensure that Python can find the OceanBase client libraries:
export LD_LIBRARY_PATH=/u01/obclient/lib/:$LD_LIBRARY_PATH
We recommend that you add this configuration to your shell configuration file (such as ~/.bashrc or ~/.zshrc) for permanent effect.
Step 5: Write the test program
Create a file named test_oracle.py and add the following content:
import cx_Oracle
# Execute SQL statements
username = 'test@oracle'
password = 'test'
oracle_connection = 'xxx.xxx.xxx.xxx:2881/TEST'
# Query and print data
conn = cx_Oracle.connect(username, password, oracle_connection)
def exec_sql(sql):
"""Test character types"""
cur = conn.cursor()
try:
cur.execute(sql)
conn.commit()
print(f"SQL executed successfully: {sql}")
except Exception as e:
print(f"SQL execution failed: {sql}")
print(f"Error message: {e}")
finally:
cur.close()
def print_data(sql):
"""Test numeric types"""
cur = conn.cursor()
try:
cur.execute(sql)
data = cur.fetchall()
print(f"Query result: {data}")
return data
except Exception as e:
print(f"Query failed: {sql}")
print(f"Error message: {e}")
return None
finally:
cur.close()
def test_char_types():
"""Test Time Type"""
print("\n=== Test character types ===")
exec_sql("DROP TABLE test_char")
exec_sql("""
CREATE TABLE test_char (
id INT,
a VARCHAR2(20),
b CHAR(10),
c NCHAR(10),
d NVARCHAR2(10)
)
""")
exec_sql("INSERT INTO test_char VALUES (1, 'hello', 'adffdf', '2df4d', 'dsf44f')")
print_data("SELECT * FROM test_char")
def test_number_types():
"""Test LOB type"""
print("\n=== Testing numeric types ===")
exec_sql("DROP TABLE test_number")
exec_sql("""
CREATE TABLE test_number (
a NUMBER,
b FLOAT(126),
c BINARY_FLOAT,
d BINARY_DOUBLE
)
""")
exec_sql("INSERT INTO test_number VALUES (12.32, 12.34, 14.23, 123.3433)")
print_data("SELECT * FROM test_number")
def test_time_types():
"""main function"""
print("\n=== Test time types ===")
exec_sql("DROP TABLE test_time")
exec_sql("""
CREATE TABLE test_time (
a DATE,
b TIMESTAMP,
c TIMESTAMP WITH TIME ZONE,
d TIMESTAMP WITH LOCAL TIME ZONE
)
""")
exec_sql("""
INSERT INTO test_time VALUES (
TIMESTAMP'2022-08-29 14:44:30',
TIMESTAMP'2022-08-29 14:44:30',
TIMESTAMP'2022-08-29 14:44:30',
TIMESTAMP'2022-08-29 14:44:30'
)
""")
print_data("SELECT * FROM test_time")
def test_lob_types():
"""Database connection information"""
print("\n=== Test LOB type ===")
exec_sql("DROP TABLE test_lob")
exec_sql("""
CREATE TABLE test_lob (
a CLOB,
b BLOB,
c RAW(100)
)
""")
exec_sql("INSERT INTO test_lob VALUES ('sdfdslkfjldsf', '31323334353637', '31323334')")
print_data("SELECT * FROM test_lob")
def main():
"""Create a database connection."""
try:
print("Starting test for connecting to OceanBase Database in Oracle-compatible mode...")
# Test various data types
test_char_types()
test_number_types()
test_time_types()
test_lob_types()
print("\nAll tests completed!")
except Exception as e:
print(f"An error occurred during the test: {e}")
finally:
# Close database connection
if conn:
conn.close()
print("Database connection is closed")
if __name__ == "__main__":
main()
Step 6: Run the test program
Run the test program in the command line:
python3 test_oracle.py
The program will test data operations for character, numeric, time, and LOB types in sequence and output the execution results.
Connection pool support
Connection pool support is available starting from OBCI 2.1.1. You can use a connection pool to improve application performance and concurrent processing capabilities.
import cx_Oracle
from cx_Oracle import SessionPool
def test_simple_pool():
"""Connection Pool Test"""
try:
print("Creating connection pool...")
# Create a connection pool
pool = SessionPool(
user="test@oracle",
password="test",
dsn="xxx.xxx.xxx.xxx:2881/TEST",
min=2,
max=5,
increment=1
)
print(f"Connection pool created successfully!")
print(f"- Minimum connections: {pool.min}")
print(f"- Maximum connections: {pool.max}")
print(f"- Increment: {pool.increment}")
print("\nTesting connection pool usage...")
# Obtain a connection from the connection pool
with pool.acquire() as connection:
with connection.cursor() as cursor:
# Execute query
cursor.execute("SELECT COUNT(*) FROM test_char")
result = cursor.fetchone()
print(f"Number of records in the test_char table: {result[0]}")
# Execute another query
cursor.execute("SELECT * FROM test_char WHERE id = 1")
data = cursor.fetchone()
print(f"Query result: {data}")
print(f"\nConnection pool status:")
print(f"- Number of open connections: {pool.opened}")
print(f"- Number of busy connections: {pool.busy}")
print("\nConnection pool test completed successfully!")
# Note: Do not call pool.close() to avoid segment faults.
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
test_simple_pool()