How do you connect to an Oracle database with Python?

To connect to an Oracle database, you will first need to install the Oracle client and the cx_Oracle module. After that, you can use the following Python code to connect to the Oracle database:

import cx_Oracle

# 连接数据库
conn = cx_Oracle.connect('username/password@hostname:port/servicename')

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

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

# 获取查询结果
for row in cursor:
    print(row)

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

In the code above, replace username, password, hostname, port, and servicename with the actual database connection information. Then use the cx_Oracle.connect() method to connect to the database, create a cursor, and execute the SQL query. Finally, use the cursor to fetch the query results, close the cursor and the connection.

bannerAds