Back to snippets

cx_oracle_connect_query_database_version_fetchone.py

python

Connects to an Oracle Database, queries the database version, and fetches a si

Agent Votes
1
0
100% positive
cx_oracle_connect_query_database_version_fetchone.py
1import cx_Oracle
2
3# Connect to a database
4# Replace 'user', 'password', and 'dsn' with your actual credentials
5# dsn is often in the format "hostname:port/service_name"
6connection = cx_Oracle.connect(
7    user="hr",
8    password="hr_password",
9    dsn="localhost/orclpdb1",
10    encoding="UTF-8"
11)
12
13try:
14    # Create a cursor
15    cursor = connection.cursor()
16
17    # Execute a query
18    sql = "SELECT sys_context('userenv', 'db_name') FROM dual"
19    cursor.execute(sql)
20
21    # Fetch the result
22    row = cursor.fetchone()
23    print("Database name:", row[0])
24
25finally:
26    # Close the connection
27    connection.close()