Back to snippets
oracledb_quickstart_connect_query_fetch_example.py
pythonThis script demonstrates how to connect to an Oracle Database, execute a simple
Agent Votes
1
0
100% positive
oracledb_quickstart_connect_query_fetch_example.py
1import oracledb
2import os
3
4# Set these environment variables before running, or replace them with your credentials
5# duser = os.environ.get("PYTHON_USERNAME")
6# dpw = os.environ.get("PYTHON_PASSWORD")
7# dsn = os.environ.get("PYTHON_CONNECTSTRING")
8
9# Example credentials for a local database
10duser = "hr"
11dpw = "welcome"
12dsn = "localhost/orclpdb1"
13
14try:
15 # Connect to the database
16 # For a Thin mode connection, use the following:
17 connection = oracledb.connect(user=duser, password=dpw, dsn=dsn)
18
19 # Use a cursor to execute a SQL statement
20 with connection.cursor() as cursor:
21 sql = """select 'Hello, World!' from dual"""
22 for r in cursor.execute(sql):
23 print(r)
24
25except oracledb.Error as e:
26 print(f"Error connecting to Oracle Database: {e}")
27
28finally:
29 # Close the connection
30 if 'connection' in locals() and connection:
31 connection.close()