新聞中心
cx_Oracle支持Python訪問Oracle數(shù)據(jù)庫。 它符合Python Database API v2.0規(guī)范 ,包含大量添加內(nèi)容和一些排除項(xiàng)。

Python程序調(diào)用cx_Oracle函數(shù)。 在內(nèi)部,cx_Oracle動(dòng)態(tài)加載Oracle客戶端庫以訪問Oracle數(shù)據(jù)庫。
下載:
1. instantclient-basic-linux.x64-11.2.0.4.0.zip
2. instantclient-sqlplus-linux.x64-11.2.0.4.0.zip
3. instantclient-sdk-linux.x64-11.2.0.4.0.zip
解壓文件放到如下目錄:
$HOME/oracle/instantclient_11_2
拷貝tnsnames.ora文件,在/home/oracle/instantclient_11_2目錄下創(chuàng)建network/admin目錄,并將tnsnames.ora文件拷貝進(jìn)去(這個(gè)貌似不是必要條件,出了問題的話就補(bǔ)上吧)
~/.bashrc設(shè)置:
export ORACLE_HOME=$HOME/oracle/instantclient_11_2
export TNS_ADMIN=$ORACLE_HOME/network/admin
export DYLD_LIBRARY_PATH=$ORACLE_HOMEexport PATH=$ORACLE_HOME:$PATH
下面就是該安裝cx_Oracle的python模塊了,下載直接python setup.py install
由于非root的權(quán)限,會(huì)報(bào)無/lib64/python2.6/site-packages/目錄讀寫權(quán)限
可以改寫python的安裝目錄
export PATH=$ORACLE_HOME:$PATH
然后source .bashrc生效
接下來可以安裝了:python setup.py install –prefix=~/.local (牛逼閃閃啊,直接在原目錄前加了個(gè)本地目錄前綴,華麗麗的解決非root的壁壘)
順其自然的又報(bào)錯(cuò)了(奔潰呀),/usr/bin/ld: cannot find -lclntsh
這個(gè)錯(cuò)誤之前在mac上裝cx_Oracle時(shí)候沒遇到,百度解決方案,得知是沒有找到lib下的libclntsh.so函數(shù)庫
其實(shí)是有的,只不過名字改了,加軟鏈接:
ln -s libclntsh.so.11.1 libclntsh.so
再次安裝解決。
補(bǔ)充:
非root安裝rpm包
首先把RPM包解壓出來,然后放在自己的目錄下,并且添加好環(huán)境變量 解壓的命令為: rpm2cpio ctags-5.8-2.el6.x86_64.rpm | cpio -idvm 這樣就會(huì)按包里的目錄結(jié)構(gòu)解壓到當(dāng)前目錄,如果是家目錄的話,可以在家目錄下的.bashrc這樣添加環(huán)境變量
-
vim ~/.bashrc
-
export PATH=$PATH:$HOME/usr/bin/
重新登錄或者source ~/.bashrc文件,就可以使用這個(gè)程序了
easy_install –prefix=~/.local cx_Oracle
卸載:
python setup.py install --record record.txt --prefix=~/.local 然后刪除record.txt里的所有文件
貼段cx_Oracle 使用代碼,作為備忘:
import cx_Oracle
class ConnectOracle:
def __init__(self, username, passwd, locate):
self.login = {}
self.db = None
self.cursor = None
self.login['username'] = username
self.login['passwd'] = passwd
self.login['locate'] = locate
def connect_oracle(self):
try:
self.db = cx_Oracle.connect(self.login['username'], self.login['passwd'], self.login['locate']) # 登錄內(nèi)搜數(shù)據(jù)庫
self.db.autocommit = False # 關(guān)閉自動(dòng)提交
self.cursor = self.db.cursor() # 設(shè)置cursor光標(biāo)
return True
except:
print 'can not connect oracle'
return False
def close_oracle(self):
self.cursor.close()
self.db.close()
def select_oracle(self, sql, num=0, temp=None):
if self.connect_oracle():
if temp:
self.cursor.executemany(sql, temp)
else:
self.cursor.execute(sql)
if num:
content = self.cursor.fetchmany(num)
else:
content = self.cursor.fetchall()
self.close_oracle()
return content
return False
def insert_oracle(self, sql, temp=None):
try:
self.connect_oracle()
if temp:
self.cursor.executemany(sql, temp)
\# 執(zhí)行多條sql命令
else:
self.cursor.execute(sql)
except:
print "insert異常"
self.db.rollback() # 回滾
finally:
self.db.commit()
self.close_oracle()
本文標(biāo)題:Python安裝并使用cx_Oracle模塊
本文來源:http://www.dlmjj.cn/article/djcijed.html


咨詢
建站咨詢
