1. Environment settings
[Email protected] ~]# cat/etc/redhat-release
CentOS Release 6.9 (Final)
[Email protected] ~]# python-v
Python 2.6.6
Version: Oracle 12c
2. Premise: Install Cx_oracle module Dependency Package
The Oracle client package needs to be downloaded due to the use of Python to connect to Oracle
Official website: HTTP://WWW.ORACLE.COM/TECHNETWORK/TOPICS/LINUXX86-64SOFT-092277.HTML?SSSOURCESITEID=OTNCN
oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm
oracle-instantclient12.1-devel-12.1.0.2.0-1.x86_64.rpm
oracle-instantclient12.1-sqlplus-12.1.0.2.0-1.x86_64.rpm
[Email protected] ~]# RPM-IVH oracle-instantclient12.1-*
3. Setting Environment variables
[email protected] ~]# cat ~/.bash_profile
Export/usr/lib/oracle/12.1/client64/export Ld_library_path=/usr/lib/oracle/12.1/client64/lib
4. Installing the Cx_oracle module
Official website:https://pypi.python.org/pypi/cx_Oracle
Cx_oracle-6.2.1.tar.gz
[Email protected] ~]# TAR-ZXVF cx_oracle-6.2.1.tar.gz [[email protected] cx_oracle-6.2.1]# python setup.py install
You may experience an error
Error:command ' gcc ' failed with exit status 1
Workaround:
Yum Install Python-devel
Yum Install Libevent-devel
5. See if the Cx_oracle module can be imported
[[email protected] ~]# python
Python 2.6.6 (r266:84292, 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "Help", "copyright", "credits" or "license" for more information.
>>> Import Cx_oracle
>>> #无报错说明成功
6. Writing Python to connect to Oracle database scripts (Oracle user, because I am here with Oracle User rights installed)
[email protected] ~]$ cat py_oracle.py
#!/usr/bin/env python#-*-coding:utf-8-*-import cx_oracle #导入模块db =cx_oracle.connect (' System/[email protected]:1521/ ORCL ') #连接user/[email protected]: Port/instancecursor = Db.cursor () #创建游标对象cursor. Execute (' Select sysdate from dual ') #执行命 Make data = Cursor.fetchone () #返回值print (' Database time:%s '% data) print output cursor.close () #关闭游标对象db. Close () #关闭数据库
7. Execute the Script
[email protected] ~]$ python py_oracle.py
Database time:2018-03-20 20:47:59
Python connects to Oracle database