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:
- To install the cx_Oracle library, you can use the pip command for installation.
- install the cx_Oracle package using pip
- Import the cx_Oracle library.
- Include cx_Oracle.
- To establish a connection with an Oracle database, you need to provide the database connection information.
- # 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) - Create a cursor object to execute SQL query statements.
- Create a cursor using the connection.
- Execute SQL query statement:
- Execute the SQL SELECT statement on the specified table using the cursor.
- Get the search results:
- 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.