python 连接 Oracle 数据库

# -*- coding: utf-8 -*-
import os
import pandas as pd
import cx_Oracle as cx
import datetime
# os.environ['path'] =  r'D:\Program Files\plsql developer8.0\instantclient_19_12'
# 设置oci路径
os.environ['path'] = './instantclient_19_12'

# 数据库连接配置
# user = 'ods'
# passwd = 'ods'
# url = '172.31.238.138:1521/orcl'

user = 'xxxx'
passwd = 'xxxx'
url = '127.0.0.1:1521/xxx'

# panas读Oracle 但是不能出现 clob字段
def pd_query_ora(sql_str:str):
    try:
        db = cx.connect(user, passwd, url)
        df: pd.DataFrame = pd.read_sql_query(sql_str, db)
        db.close()
        isbool:bool = True
        return df,isbool
    except Exception as e:
        # print(e)
        isbool:bool = False
        return pd.DataFrame(data=[]),isbool

# lis读Oracle 可以能出现 clob字段
def read_sql(sqlstr:str):
    conn = cx.connect(user, passwd, url)
    cur = conn.cursor()
    cur.execute(sqlstr)
    rels = []
    for tup in cur:
        pram = []
        for itm in tup:
            if type(itm) == cx.LOB:
                text = itm.read()
                pram.append(text)
            elif type(itm)==datetime.datetime:
                # print(itm)
                text = datetime.datetime.strftime(itm,'%Y-%m-%d %H:%M:%S')
                pram.append(text)
            else:
                pram.append(itm)
        rels.append(pram)
    cur.close()
    conn.close()
    return rels

  

posted @ 2022-04-25 12:47  洺剑残虹  阅读(106)  评论(0编辑  收藏  举报