標籤:Python 串連 Oracle資料庫
1.環境設定
[[email protected] ~]# cat /etc/redhat-release
CentOS release 6.9 (Final)
[[email protected] ~]# 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
[[email protected] ~]# rpm - ivh oracle-instantclient12.1-*
3.設定環境變數
[[email protected] ~]# cat ~/.bash_profile
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
[[email protected] ~]# tar -zxvf cx_Oracle-6.2.1.tar.gz [[email protected] 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模組
[[email protected] ~]# 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使用者權限安裝的)
[[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]:連接埠/instancecursor = db.cursor() #建立遊標對象cursor.execute('select sysdate from dual') #執行命令data = cursor.fetchone() #傳回值print('Database time:%s' % data) 列印輸出cursor.close() #關閉遊標對象db.close() #關閉資料庫
7.執行指令碼
[[email protected] ~]$ python py_oracle.py
Database time:2018-03-20 20:47:59
Python 串連 Oracle資料庫