python连接oracle数据库封装类_Python Oracle连接与操作封装

本文介绍了两种Python连接Oracle数据库并进行操作的封装方法。第一种通过cx_Oracle库实现连接、查询、DML操作及关闭连接。第二种方法同样使用cx_Oracle库,增加了JSON输出功能,以及insert、update、delete方法。
摘要由CSDN通过智能技术生成

一、封装方式一

#encoding:utf-8

import cx_Oracle

class Oracle_Status_Output:

def __init__(self,db_name,db_password,db_tns):

try:

self.db = cx_Oracle.connect(db_name,db_password,db_tns)

self.cursor = self.db.cursor()

except Exception as e:

print('Wrong')

print(e)

def oracle_status_select(self,sql):

try:

self.cursor.execute(sql)

col=col=self.cursor.description

v_result=self.cursor.fetchall()

return v_result,col

except Exception as e:

print(e)

def oracle_status_dml(self,sql):

try:

self.cursor.execute(sql)

self.db.commit()

print("DML OK")

except Exception as e:

print(e)

def close(self):

self.cursor.close()

self.db.close()

二、封装方式二

#  coding=utf-8

import cx_Oracle

import os

import json

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

"""python version 3.7"""

class TestOracle(object):

def __init__(self, user, pwd, ip, port, sid):

self.connect = cx_Oracle.connect(user + "/" + pwd + "@" + ip + ":" + port + "/" + sid)

self.cursor = self.connect.cursor()

def select(self, sql):

list = []

self.cursor.execute(sql)

result = self.cursor.fetchall()

col_name = self.cursor.description

for row in result:

dict = {}

for col in range(len(col_name)):

key = col_name[col][0]

value = row[col]

dict[key] = value

list.append(dict)

js = json.dumps(list, ensure_ascii=False, indent=2, separators=(',', ':'))

return js

def disconnect(self):

self.cursor.close()

self.connect.close()

def insert(self, sql, list_param):

try:

self.cursor.executemany(sql, list_param)

self.connect.commit()

print("插入ok")

except Exception as e:

print(e)

finally:

self.disconnect()

def update(self, sql):

try:

self.cursor.execute(sql)

self.connect.commit()

except Exception as e:

print(e)

finally:

self.disconnect()

def delete(self, sql):

try:

self.cursor.execute(sql)

self.connect.commit()

print("delete ok")

except Exception as e:

print(e)

finally:

self.disconnect()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值