python灵活连接数据库,返回字典结果

#add by Dob
#python 3.6.2
#oracle 64windows
import cx_Oracle as orcl
class OraDao(object):
    def switch(self):
        db = {}
        db['xe']="system/123456@XE"
       
        return db[self.db_name]
    def __init__(self,db_name):
        print('初始化%s中。。。' % db_name)
        self.db_name=db_name

    def makedict(self, cursor):
        result = cursor.fetchall()
        cur_desc = cursor.description
        colum = {}
        #print(cur_desc.__len__())
        for i in range(cur_desc.__len__()):
            for n in range(result.__len__()):
                try:
                    rs=result[n][i]
                except Exception as e:
                    print(e)
            colum[cur_desc[i][0]] = rs
        return colum

    def dh_ddl(self,sql,bind):
        mydict={}
        try:
            conn = orcl.connect(self.switch())
            cur = conn.cursor();
            # print(sql)
            cur.execute(sql, bind)
            mydict = self.makedict(cur)
            cur.close();
            conn.close();
        except Exception as e:
            #print(e)
            error_info = str(e).split(":", 1)
            #print(error_info)
            mydict['Error_Code']=error_info[0]
            mydict['Error_Info'] = error_info[1]
        return mydict

oraDao=OraDao('xe')
sql='select user_name,subscription_id,service_type,service_status from ucs_subscription ' \
        'where service_num=:service_num'
bind={'service_num':'15501951002'} #本人号码
print(oraDao.dh_ddl(sql,bind))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值