• py读取Oracle数据库数据方法


    # -----------------封装读取Oracle数据库数据-----------------
    # coding:utf-8
    import cx_Oracle
    import os

    os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
    print("cx_Oracle版本:", cx_Oracle.clientversion())

    u'''Oracle数据库相关操作
    连接数据库名称如:xxx
    查询数据:oracle_getrows
    查询某个字段对应的字符串:oracle_getstring
    执行sql语句:oracle_sql
    关闭oracle连接:oracle_close
    '''
    dbname = {"user": "wapn_czth",
    "pwd": "123456",
    "dsn": "127.0.0.1:1521/ORCL"}

    class OracleUtil():
    def __init__(self):
    ''' 连接池方式'''
    self.db_info = dbname
    self.conn = OracleUtil.__getConnect(self.db_info)

    @staticmethod
    def __getConnect(db_info):
    ''' 静态方法,从连接池中取出连接'''
    try:
    con = cx_Oracle.connect(db_info['user'], db_info['pwd'], db_info['dsn'])
    return con
    except Exception as a:
    print("数据库连接异常:%s"%a)

    def oracle_getrows(self, sql):
    ''' 执行查询sql'''
    try:
    cursor = self.conn.cursor()
    try:
    cursor.execute(sql)
    rows = cursor.fetchall()
    return rows
    except Exception as a:
    print("执行sql出现异常:%s"%a)
    finally:
    cursor.close()
    except Exception as a:
    print("数据库连接异常:%s"%a)

    def oracle_getstring(self, sql):
    ''' 查询某个字段的对应值'''
    rows = self.oracle_getrows(sql)
    if rows != None:
    for row in rows:
    for i in row:
    return i

    def oracle_sql(self, sql):
    ''' 执行sql语句'''
    try:
    cursor = self.conn.cursor()
    try:
    cursor.execute(sql)
    except Exception as a:
    print("执行sql出现异常:%s" % a)
    finally:
    cursor.close()
    except Exception as a:
    print("数据库连接异常:%s" % a)


    def orcle_close(self):
    ''' 关闭orcle连接'''

    try:
    self.conn.close()
    except Exception as a:
    print("数据库关闭时异常:%s"%a)

    if __name__ == "__main__":
    oracl = OracleUtil()
    sql = "select t.union_id from th_user_info t where t.union_id is not null"
    s = oracl.oracle_getrows(sql)
    print(type(s))
    for j in s:
    for i in j:
    r = print("union_id:", i)

    oracl.orcle_close()
  • 相关阅读:
    简约 高效 基层管理体制
    六大纪律
    平行文
    党章
    四大考验 四大危险
    创新、协调、绿色、开放、共享五大发展理念
    微信公众号-->微信html页面缓存问题
    本地kafka环境部署
    >>读懂一本书:樊登读书法>>-->摘抄
    海龟交易法则(第3版)-->摘抄
  • 原文地址:https://www.cnblogs.com/wapn/p/9613519.html
Copyright © 2020-2023  润新知