Python 连接 Oracle 并实现增删改查(cx_Oracle)
import cx_Oracle
# 连接Oracle数据库
def connect_oracle(username, password, host, port, service_name):
dsn = cx_Oracle.makedsn(host, port, service_name)
connection = cx_Oracle.connect(username, password, dsn)
return connection
# 查询Oracle数据库
def query_oracle(connection, query):
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
return result
# 在Oracle数据库中插入数据
def insert_oracle(connection, table_name, data):
cursor = connection.cursor()
columns = ', '.join(data.keys())
values = ', '.join(':' + column for column in data.keys())
sql = f"INSERT INTO {table_name} ({columns}) VALUES ({values})"
cursor.execute(sql, data)
connection.commit()
cursor.close()
# 在Oracle数据库中更新数据
def update_oracle(connection, table_name, data, condition):
cursor = connection.cursor()
updates = ', '.join(f"{key} = :{key}" for key in data.keys())
sql = f"UPDATE {table_name} SET {updates} WHERE {condition}"
cursor.execute(sql, data)
connection.commit()
cursor.close()
# 在Oracle数据库中删除数据
def delete_oracle(connection, table_name, condition):
cursor = connection.cursor()
sql = f"DELETE FROM {table_name} WHERE {condition}"
cursor.execute(sql)
connection.commit()
cursor.close()
# 示例用法
if __name__ == "__main__":
# 替换以下信息为你的数据库连接信息
username = "your_username"
password = "your_password"
host = "your_host"
port = "your_port"
service_name = "your_service_name"
# 连接数据库
connection = connect_oracle(username, password, host, port, service_name)
# 查询示例
query = "SELECT * FROM your_table"
result = query_oracle(connection, query)
print(result)
# 插入示例
data = {'column1': 'value1', 'column2': 'value2'}
insert_oracle(connection, 'your_table', data)
# 更新示例
update_data = {'column1': 'new_value1'}
update_condition = "column2 = 'value2'"
update_oracle(connection, 'your_table', update_data, update_condition)
# 删除示例
delete_condition = "column1 = 'new_value1'"
delete_oracle(connection, 'your_table', delete_condition)
# 关闭数据库连接
connection.close()
在这个代码示例中,我们首先定义了连接Oracle数据库的函数connect_oracle
,然后是查询数据库的query_oracle
函数。接着,我们实现了insert_oracle
用于插入数据,\`upd
评论已关闭