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))

你可能感兴趣的:(python)