To read data from an
Oracle database in Python, you can use the `cx_Oracle` or sqlachemy library.
Here's an example of how to connect to the database and retrieve data using
cx_oracle library:
user="your_username",
password="your_password",
dsn="your_host:your_port/service_name"
)
cursor.execute(query)
Replace
`"your_table"` with the name of the table you want to retrieve data
from, and `"column1"` and `"column2"` with the names of the
columns you want to select.
# row = cursor.fetchone()
for row in result_set:
column1_value =
row[0] # Access values by index
column2_value =
row[1]
print(column1_value, column2_value)
8. Close the cursor and
the database connection when you're done:
connection.close()
This is a sample example
of how to read data from an Oracle database in Python using the `cx_Oracle`
library. You can expand on this example to handle different types of queries
and process the data according to your needs.
Below is the complete python code.
import cx_Oracle
def
read_from_oracle_table(connection_string, query):
try:
# Establish a connection to the Oracle database
connection = cx_Oracle.connect(connection_string)
# Create a cursor object to execute SQL queries
cursor = connection.cursor()
# Execute the SQL query to fetch data from the table
cursor.execute(query)
# Fetch all the rows from the query result
rows = cursor.fetchall()
# You can process and manipulate the 'rows' data as needed here
for row in rows:
print(row) # Print each row to the console as an
example
except
cx_Oracle.Error as error:
print(f"Error: {error}")
finally:
# Close the cursor and the database connection
if cursor:
cursor.close()
if connection:
connection.close()
# Usage example:
if __name__ ==
"__main__":
connection_string = "your_username/your_password@your_database_url"
query =
"SELECT * FROM your_table_name"
read_from_oracle_table(connection_string, query)
0 Comments
Thanks for your message.