Fedora 29 系统使用 Python3 连接Oracle 11.2数据库

Published: 2019-07-02

Tags: Python

本文总阅读量

1)下载连接客户端(instant_client)

Oracle下载 Github 下载

我下载的zip包名为:instantclient-basic-linux.x64-19.3.0.0.0dbru.zip

2)进行配置

官方教程:https://oracle.github.io/odpi/doc/installation.html#oracle-instant-client-zip

简要说明:

  1. 将解压后的 instantclient_19_3 文件夹放置在 /opt/oracle 目录下

  2. 安装 libaio 包(命令:dnf install libaio

  3. 创建链接配置

shell sudo sh -c "echo /opt/oracle/instantclient_19_3 > /etc/ld.so.conf.d/oracle-instantclient.conf" sudo ldconfig

  1. 创建环境变量 shell LD_LIBRARY_PATH=/opt/oracle/instantclient_19_3:$LD_LIBRARY_PATH

3)安装三方包

pip3 install cx_Oracle --user

4)示例代码

# -*- coding: utf-8 -*-

import cx_Oracle

import os
# 解决检索出的数据中文乱码
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

try:
    dsnStr = cx_Oracle.makedsn("192.168.3.216", "1521", "thesid")
    con = cx_Oracle.connect(user="username", password="password", dsn=dsnStr)

    cursor = con.cursor()

    sql_string = 'select * from table_name'

    cursor.execute(sql_string)
    data = cursor.fetchall()
    for one in data:
        print(one)

    print(con.version)

    con.commit()
    cursor.close()
    con.close()

except cx_Oracle.DatabaseError as e:
    print("There is a problem with Oracle", e)

5)创建软连接

运行示例代码会报错

DPI-1047: 64-bit Oracle Client library cannot be loaded: "libnsl.so.1: cannot open shared object file: No such file or directory".

我在这个网址里面找到了原因:https://github.com/oracle/node-oracledb/issues/892

在 Fedora 高版本里这个动态库修改了名字

解决办法:创建软连接

ln -s /usr/lib64/libnsl.so.2.0.0 /usr/lib64/libnsl.so.1

用Python3连接Oracle数据库,网上找到很多不靠谱的资料 ORACLE_HOME,加PATH什么的... 记录一下