Using Python to Operate Oracle
To use Python to operate Oracle Database, we need to install ` cx_ Oracle ` library` Cx_ Oracle 'is a third-party library used to connect and operate Oracle Database.
The following is a complete Python code example that demonstrates how to connect to the Oracle Database and insert, query, modify, and delete data.
python
import cx_Oracle
#Connect to Oracle Database
Dsn=cx_ Oracle. makedsn (host='localhost ', port='1521', sid='ORCL ') # Replace with your database connection information
Conn=cx_ Oracle. connect (user='username ', password='password', dsn=dsn) # Replace with your username and password
#Create Cursor
cursor = conn.cursor()
#Create Table
create_table_query = """
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
email VARCHAR2(100)
)
"""
cursor.execute(create_table_query)
#Insert Data
insert_data_query = """
INSERT INTO employees (employee_id, first_name, last_name, email)
VALUES (:id, :first_name, :last_name, :email)
"""
data = [
{'id': 1, 'first_name': 'John', 'last_name': 'Doe', 'email': 'john.doe@example.com'},
{'id': 2, 'first_name': 'Jane', 'last_name': 'Smith', 'email': 'jane.smith@example.com'}
]
cursor.executemany(insert_data_query, data)
conn.commit()
#Query data
select_data_query = "SELECT * FROM employees"
cursor.execute(select_data_query)
result = cursor.fetchall()
for row in result:
print(row)
#Modify data
update_data_query = """
UPDATE employees
SET email = :email
WHERE employee_id = :id
"""
update_data = {'email': 'new.email@example.com', 'id': 1}
cursor.execute(update_data_query, update_data)
conn.commit()
#Delete data
delete_data_query = "DELETE FROM employees WHERE employee_id = :id"
delete_data = {'id': 2}
cursor.execute(delete_data_query, delete_data)
conn.commit()
#Close cursors and connections
cursor.close()
conn.close()
This is a simple example that demonstrates how to create tables, insert data, query data, modify data, and delete data. You can expand and modify according to your own needs.