Python 串連 Oracle資料庫

來源:互聯網
上載者:User

標籤: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資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.