cx_Oracle模块封装

About cx_Oracle

    cx_Oracle is a Python extension module that enables access to Oracle Database. It conforms to the Python database API 2.0  specification with a considerable number of additions and a couple of exclusions.


# coding:utf-8

"""
db.py
contains some oracle database operations
"""

import cx_Oracle 
# customer definition exception
from exception import IdbError
#log some info to some file
from logger import Logger
import os, sys, re

DB_STRING = cx_Oracle.STRING
DB_NUMBER = cx_Oracle.NUMBER
DB_DATETIME = cx_Oracle.DATETIME

class Param:
    """
        store procedures paraments class
    """
    def __init__(self, para_type, value, out=False):
        if para_type not in [DB_STRING, DB_NUMBER, DB_DATETIME]:
            raise IdbError("%s is not a valid para type %s" % para_type)
        self.param_type = para_type
        self.value = value
        self.out = out

class DB:
    """
        oracle db class
    """
    logger = Logger("/path/to/your/log/path","db")
    def __init__(self, username, pwd, dsn):
        self.username = username
        self.pwd = pwd
        self.dsn = dsn    
        self.__conn__ = None
        self.__cursor__ = None
    
    def open_connection(self):
        ora_str = self.username+'/'+self.pwd+self.dsn
        try:
            self.__conn__ = cx_Oracle.connect(ora_str)
        except Exception as e:
            DB.logger.log_error("connect to DB failed %s" % str(e))
            raise IdbError("connect to DB failed %s" % str(e))
        self.__cursor__ = self.__conn__.cursor()

    def close_connection(self):
        try:
            if self.__conn__:
                self.__conn__.close()
            if self.__cursor__:
                self.__cursor__.close()
        except Exception as e:
            pass

    def select(self, statement, **paraments):
        self.open_connection()
        try:
            self.__cursor__.execute(statement, paraments)
            rs = self.__cursor__.fetchall()
        except Exception as e:
            pass
        finally:
            self.close_connection()
        print(rs)
        return rs
    
    
    def select_onerow(self, statement, **paraments):
        self.open_connection()
        try:
            self.__cursor__.execute(statement, paraments)
            rs = self.__cursor__.fetchone()
        except Exception as e:
            pass
        finally:
            self.close_connection()
        if rs:
            print(rs)
            return rs   
        else: return None

    def exec_update(self, statement, **paraments):
        self.open_connection()
        try:
            self.__cursor__execute(statement, paraments)
            self.__conn__.commit()
        except Exception as e:
            pass
        finally:
            rowcount = self.__cursor__.rowcount
            self.close_connection()
        return rowcount
    
     def callsp(self, proc, *params):
        self.open_connection()
        # construct parament list
        param_array = ()
        for param in params:
            p = self.__cursor__.var(param.param_type)
            print(p)
            if not param.out:
                p.setvalue(0, param.value)
            param_array +=p
        # call store procedure
        try:
            self.__cursor__.callproc(proc, param_array)
            for i,param in enumerate(params):
                if param.out:
                    param.value = param_array[i].getvalue()
        except Exception as e:
            print(e)
        finally:
            self.close_connection()
 
if __name__ == '__main__':
    dsn = "mydsn"
    username = "oracleman"
    pwd = 'oracleman'
    proc = 'myproc'
    str1 = Param(DB_STRING, 'tm')
    str2 = Param(DB_STRING, '', True)
    ora = DB(username, pwd, dsn0
    ora.callsp(proc, str1, str2)
    ora.select("select * from tablename")
    ora.select_onerow("your statement here")
    

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你抱着的是只熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值