用python連線oracle(11g)資料庫
阿新 • • 發佈:2019-02-17
準備:
1、下載對應版本的oracle-instantclient(我這裡是11.2.0.1.0)
http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
2、安裝
rpm -ivh oracle-instantclient11.2-basic-11.2.0.1.0-1.x86_64.rpm
3、配置環境變數
#export ORACLE_BASE=/usr/lib/oracle
export ORACLE_HOME=/usr/lib/oracle/11.2/client64
export PATH=$ORACLE_HOME/bin:$PATH
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH
4、開始你的開發(我們用python)
開發:
python連線oracle資料庫需要cx_Oracle
1、下載
http://sourceforge.net/projects/cx-oracle/
2、安裝
我下載rpm包,安裝很簡單
rpm -ivh cx_Oracle-5.1.2-11g-py26-1.x86_64.rpm
3、開始你的開發吧
Python 2.6.6 (r266:84292 , Jan 22 2014, 09:42:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_Oracle
>>>
最後做了個封裝:
import cx_Oracle
class oracleAPI:
# 建構函式
def __init__(self, user, pwd, ip, port, sid):
self.__user = user
self.__pwd = pwd
self.ip = ip
self.__port = port
self.__sid = sid
self.__dsn = self.get_dsn()
self.__db = self.get_conn()
self.__curs = self.get_curs()
# 解構函式
def __del__(self):
self.__curs.close()
print 'Cursor closed.'
self.__db.close()
print 'db closed.'
# 方法
def get_dsn(self):
dsn = cx_Oracle.makedsn(self.ip, self.__port, self.__sid)
return dsn
def get_conn(self):
db = cx_Oracle.connect(self.__user, self.__pwd, self.__dsn)
return db
def get_curs(self):
curs = self.__db.cursor()
return curs
def get_db_version(self):
return self.__db.version
def execute(self, sql):
result = self.__curs.execute(sql)
return result
def main():
user = '**ystem'
pwd = '**acle'
ip = '*.*.1.25'
port = '1521'
sid = '**yb'
oapi = oracleAPI(user, pwd, ip, port, sid)
print oapi.get_db_version()
result = oapi.get_curs().execute('select * from dba_users')
print result.fetchmany()
if __name__ == "__main__":
main()
補充:應用報錯崩潰
ORA-24550: signal received: [si_signo=11] [si_errno=0] [si_code=1] [si_int=-257149584] [si_ptr=0x7f8af0ac3570] [si_addr=0x2740]
因為server上裝的是oracle basic client所以沒有sqlnet.ora所以要自己建立一個,而且要有環境變數
上邊的環境變數要增加一個
export TNS_ADMIN=$ORACLE_HOME/network/admin
然後在admin資料夾裡面建立一個檔名字為sqlnet.ora
內容:
DIAG_ADR_ENABLED=FALSE
DIAG_SIGHANDLER_ENABLED=FALSE
DIAG_DDE_ENABLED=FALSE
重啟django應用,正常