python fetches data from an Oracle database

To read Oracle database data in Python, you need to install and import the appropriate library. One common method is as follows:

  1. To install the cx_Oracle library, you can use the pip command for installation.
  2. install the cx_Oracle package using pip
  3. Import the cx_Oracle library.
  4. Include cx_Oracle.
  5. To establish a connection with an Oracle database, you need to provide the database connection information.
  6. # Connection Details
    host = ‘localhost’
    port = 1521
    service_name = ‘ORCL’
    user = ‘username’
    password = ‘password’

    # Establishing Connection
    dsn = cx_Oracle.makedsn(host, port, service_name=service_name)
    connection = cx_Oracle.connect(user, password, dsn)

  7. Create a cursor object to execute SQL query statements.
  8. Create a cursor using the connection.
  9. Execute SQL query statement:
  10. Execute the SQL SELECT statement on the specified table using the cursor.
  11. Get the search results:
  12. Retrieve all the data from the cursor and store it in a variable named “result”.

The complete example code is as follows:

import cx_Oracle

# 连接信息
host = 'localhost'
port = 1521
service_name = 'ORCL'
user = 'username'
password = 'password'

# 建立连接
dsn = cx_Oracle.makedsn(host, port, service_name=service_name)
connection = cx_Oracle.connect(user, password, dsn)

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

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

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

# 打印查询结果
for row in result:
    print(row)

# 关闭连接
cursor.close()
connection.close()

Please replace the host, port, service_name, user, and password with the actual database connection information, and replace table_name with the name of the table to be queried.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds