Connecting Python to an Oracle database can be very useful when developing applications and projects. Oracle is one of the most popular and robust database management systems on the market, while Python is a versatile and powerful programming language. In this article, we will learn how to establish a connection from Python to an Oracle database and explore code examples for performing DML (Data Manipulation Language) actions such as queries and updates. We will also learn some best practices for using these resources efficiently.
1. Installation and Configuration
The first step is to install the Oracle Instant Client on your system. This client provides the libraries needed to establish a connection to the Oracle database from Python.
-
Download the Oracle Instant Client from the official Oracle website. Make sure to choose the version compatible with your operating system and architecture (AMD or ARM; for information about architectures, see this previous article).
-
Once downloaded, extract the files into a directory of your choice. On Linux, for example, you can use
/opt/oracle/instantclient. -
Configure the environment variables so Python can find the Instant Client libraries. This can be done by adding the path to the directory where you extracted the files to the
LD_LIBRARY_PATHenvironment variable.
export LD_LIBRARY_PATH=/opt/oracle/instantclient_19_3:$LD_LIBRARY_PATH
export ORACLE_HOME=/opt/oracle/instantclient_19_3
export PATH=$PATH:$ORACLE_HOME
Additionally, we must make sure that Python is installed on our system. We will also need the appropriate driver to connect to the Oracle database. We can use the “cx_Oracle” module, which is widely used and compatible with multiple versions of Python and Oracle.
To install the “cx_Oracle” module, run the following command in the terminal:
pip install cx_Oracle
Once installed, we will need to establish the connection using the Oracle database details, such as the username, password, server address, and port number.
2. Establishing the Connection
Let us look at an example of establishing a connection to an Oracle database from Python:
import cx_Oracle
# Connection details
username = 'username'
password = 'password'
server = 'server_address/database_name'
# Establish connection
connection = cx_Oracle.connect(username, password, server)
# Close connection
connection.close()
It is important to remember to close the connection after using it so resources are released correctly.
3. Running DML Actions
Once we have established the connection, we can execute DML actions on the Oracle database, such as SELECT queries, UPDATE statements, or INSERT statements.
Let us look at an example of running a SELECT query:
import cx_Oracle
# Establish connection
connection = cx_Oracle.connect(username, password, server)
# Create cursor
cursor = connection.cursor()
# Execute SELECT query
cursor.execute('SELECT column1, column2 FROM table_name')
# Fetch results
results = cursor.fetchall()
# Display results
for row in results:
print(row)
# Close cursor
cursor.close()
# Close connection
connection.close()
Similarly, we can run updates or inserts using the appropriate statements, making sure to confirm changes with the commit() method and handle possible errors using a try-except-finally structure.
4. Best Practices
When using Python to connect to an Oracle database, it is important to follow some best practices:
-
Use prepared statements: Instead of directly concatenating values into SQL queries, it is recommended to use prepared statements. This helps prevent SQL injection attacks and improves query efficiency.
-
Handle errors properly: It is essential to handle errors appropriately when connecting to the database and executing DML actions. Using
try-except-finallyblocks allows us to catch and handle errors effectively, as well as ensure that the connection is closed and resources are released properly. -
Implement business logic in Python: Instead of performing complex data manipulation operations directly in the database, it is recommended to use Python’s capabilities to implement business logic. This simplifies code maintenance and scalability.
-
Optimize queries: When designing SQL queries, it is important to optimize them to improve performance. Using appropriate indexes, limiting the amount of data retrieved, and avoiding unnecessary queries will help achieve better response times.
-
Close connections and cursors correctly: To avoid resource leaks, it is essential to close connections and cursors once we have finished using them. This ensures that resources are released properly and prevents performance problems.
Conclusion
Connecting Python to an Oracle database gives us the ability to take advantage of both resources to develop efficient and scalable applications. In this article, we explored how to establish a connection from Python to an Oracle database, execute DML actions, and follow best practices for optimal use of these resources. Remember to install the appropriate driver, establish the connection correctly, execute DML actions safely, and close connections and cursors properly. With this foundation, you can develop robust and efficient applications that take advantage of the power of Python and the Oracle database.
I hope this article has been useful. Good luck on your development journey with Python and Oracle databases!

