You can connect to Oracle from Python using Devart ODBC Driver for Oracle.
Run the following command to install the pyodbc
library.
pip install pyodbc
An ODBC connection requires a connection string, which can either use a predefined DSN or be specified through connection string parameters (a DSN-less connection).
For information about available parameters, see Connection string parameters.
You can use a connection string with a predefined DSN.
connectionString = "DSN=your_dsn"
If you need credentials other than those used in the DSN, specify them in the connection string to override the DSN values.
connectionString = "DSN=your_dsn;User ID=your_username;Password=your_password"
For information on configuring a DSN on specific operating systems, see instructions for Windows, macOS, or Linux.
You can establish a connection without a DSN by specifying all necessary parameters directly in the connection string.
The following example uses Direct connection.
connectionString = "DRIVER=Devart ODBC Driver for Oracle;Direct=True;Host=your_server;Service Name=your_service_name;User ID=your_username;Password=your_password"
For more information, see DSN-less connections.
The following Python code demonstrates how to connect to Oracle and fetch data using the ODBC driver.
# Import the pyodbc library for ODBC connections
import pyodbc
# Define an ODBC connection string
connectionString = "your_connection_string"
connection = pyodbc.connect(connectionString)
# Create an object to interact with a data source
cursor = connection.cursor()
# Execute a SQL query
query = "SELECT DEPTNO, DNAME FROM DEPT"
cursor.execute(query)
# Fetch and print the query results
print("Query results:")
for row in cursor.fetchall():
# Output each tuple of the query results to the console
print(row)
# Close the cursor and the connection
cursor.close()
connection.close()