Python 連接 Oracle數據庫


1.環境設置

[root@oracle ~]# cat /etc/redhat-release 

CentOS release 6.9 (Final)

[root@oracle ~]# python -V

Python 2.6.6

版本:Oracle 12c

 

2.前提:安裝cx_Oracle模塊依賴包

由於使用Python連接Oracle,所以需要下載oracle客戶端包

官網: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

1
[root@oracle ~] # rpm - ivh oracle-instantclient12.1-*

 

3.設置環境變量

[root@oracle ~]# cat ~/.bash_profile 

1
2
export  /usr/lib/oracle/12 .1 /client64/
export  LD_LIBRARY_PATH= /usr/lib/oracle/12 .1 /client64/lib

 

4.安裝cx_Oracle模塊

官網:https://pypi.python.org/pypi/cx_Oracle

cx_Oracle-6.2.1.tar.gz 

1
2
[root@oracle ~] # tar -zxvf cx_Oracle-6.2.1.tar.gz 
[root@oracle cx_Oracle-6.2.1] # python setup.py install

可能會遇到報錯

error: command 'gcc' failed with exit status 1

解決方法:

yum install python-devel

yum install libevent-devel

 

5.查看是否可以導入cx_Oracle模塊

[root@oracle ~]# python

Python 2.6.6 (r266:84292, Aug 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.編寫Python連接oracle數據庫腳本(oracle用戶,因為我這里都是用oracle用戶權限安裝的)

[oracle@oracle ~]$ cat py_oracle.py 

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import  cx_Oracle   #導入模塊
db=cx_Oracle.connect( 'system/oracle@localhost:1521/ORCL' )   #連接user/passwd@host:端口/instance
cursor = db.cursor()  #創建游標對象
cursor.execute( 'select sysdate from dual' )   #執行命令
data = cursor.fetchone()  #返回值
print( 'Database time:%s'  % data)  打印輸出
cursor.close()   #關閉游標對象
db.close()   #關閉數據庫

 

7.執行腳本

[oracle@oracle ~]$ python py_oracle.py 

1
Database  time :2018-03-20 20:47:59


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM