Python Oracle Database: Retrieve Data Guide

To retrieve data from an Oracle database, you can use the cx_Oracle module in Python.

Firstly, make sure that the cx_Oracle module has been installed. You can install it using the following command:

pip install cx_Oracle

Next, use the following code example to retrieve data from an Oracle database:

import cx_Oracle

# 建立与数据库的连接
conn = cx_Oracle.connect('username/password@host:port/service_name')

# 创建游标对象
cursor = conn.cursor()

# 执行SQL查询语句
cursor.execute('SELECT * FROM table_name')

# 获取查询结果
result = cursor.fetchall()

# 遍历结果并打印
for row in result:
    print(row)

# 关闭游标和连接
cursor.close()
conn.close()

In the code, actual database connection information should be substituted for username, password, host, port, and service_name. The table_name should be replaced with the actual table name.

The fetchall() method is used to retrieve all query results and returns a list containing all rows. Alternatively, the fetchone() method can be used to retrieve one row of results, or the fetchmany(size) method can be used to retrieve a specified number of results, depending on the actual needs.

Finally, remember to close the cursor and connection after using them to release resources.

Prior to using the cx_Oracle module, Oracle Instant Client may need to be installed. For specific installation steps, please refer to the official documentation of cx_Oracle.

bannerAds