Fork me on GitHub

Ubuntu16安装cx_Oracle

最近想用python3写点自动化测试的东西,要连接oracle数据库,google了一番,发现目前cx_Oracle这个包比较好,恰好最近也添加了对python3.6的支持。
下面是我的安装之旅。

本机环境

  • OS: Ubuntu 16.04.2

  • python: Python 3.6.1

安装cx_Oracle

cx_Oracle is a Python extension module that enables access to Oracle Database and conforms to the Python database API specification. This module is currently built against Oracle Client 11.2, 12.1 and 12.2 and Python 2.7, 3.4, 3.5 and 3.6. For more information on the database API specification, see here.

安装命令:

python -m pip install cx_Oracle --pre

OK,安装成功,于是兴冲冲的我在SublimeText3敲下hello world:

import cx_Oracle

# connect to oracle
conn = cx_Oracle.connect('username/password@oracle-db-path')
cursor = conn.cursor()
cursor.execute("SELECT 1 FROM DUAL")
rs = cursor.fetchone()
print('result=%s' % rs)

#close all resource
cursor.close()
conn.close()

ctrl+b执行,果然报错:

ImportError: No module named cx_Oracle

一查,发现是没有安装oracle instant client导致的。接下来就是安装它。

安装Oracle Instant Client

官方下载

官网上写着几个大字:新版本12.2发布啦!好嘛,用新不用旧可谓程序员的浪漫,就装他了!
下载以下几个包:

oracle-instantclient12.2-basic-12.2.0.1.0-1.x86_64.rpm
oracle-instantclient12.2-devel-12.2.0.1.0-1.x86_64.rpm
oracle-instantclient12.2-sqlplus-12.2.0.1.0-1.x86_64.rpm

因为是rpm包,所以需要用alien工具安装,如果没装,那么:

sudo apt install alien

接下来用alien安装rpm包:

sudo alien -i oracle-instantclient12.2-basic-12.2.0.1.0-1.x86_64.rpm
sudo alien -i oracle-instantclient12.2-devel-12.2.0.1.0-1.x86_64.rpm
sudo alien -i oracle-instantclient12.2-sqlplus-12.2.0.1.0-1.x86_64.rpm

安装完毕后,在安装目录建立network/admin目录

cd /usr/lib/oracle/12.2/client64
sudo mkdir -p network/admin

修改/etc/environment

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/oracle/12.2/client64/bin"
ORACLE_HOME="/usr/lib/oracle/12.2/client64"
OCI_LIB="$ORACLE_HOME/lib"
TNS_ADMIN="$ORACLE_HOME/network/admin"

source一下,接下来修改动态连接库

 echo "/usr/lib/oracle/12.2/client64/lib" | sudo tee /etc/ld.so.conf.d/oracle.conf
 sudo ldconfig -v

安装额外支持包

 sudo apt-get install libaio1

测试:

sqlplus username/password@site

然而我失败了,倒不是因为安装问题,单纯只是因为目标数据库是9i版本的,而12.2已经不再支持这个版本的数据库了。
fuck!!!

既然到了这一步,还是继续往下走吧,因为python import还需要一点额外的工作:

$ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/oracle/12.2/client64/lib python -c "import cx_Oracle; print(cx_Oracle.version)"

参考资料

  1. Ubuntu14.04安装Oracle Instant Client

  2. how to install Oracle instant client in Ubuntu16

  3. cx_Oralce官方网站

  4. Version 6 fails to find OCI libs where version 5 succeeded

posted @ 2017-06-22 17:35  alchimistin  阅读(427)  评论(0编辑  收藏  举报