[Oracle] Python 連接Oracle數據庫,操作及問題解決方法


必需的Oracle鏈接庫的下載地址:https://www.oracle.com/technetwork/topics/winx64soft-089540.html

只連接數據庫的話不必安裝客戶端:

1. 把cx_Oracle的客戶端文件復制到site-packages/ 目錄下,可能是Python, Anaconda, venv下面的安裝包里

2. 把下載的instantclient文件夾下的oci.dll, oraocci12.dll,oraociei12.dll文件復制到site-packages/ 目錄下

3. 把instantclient文件解壓后的地址添加到環境變量里面去。

4. 創建數據庫連接.

注:oracle18和orcale12.2版本的需下載安裝vs2013,否則報:

1、無法啟動此程序,因為計算機丟失MSVCP120.dll,MSVCR120.dll

2、“64-bit Oracle Client library cannot be loaded: "The specified module could not be”

創建數據庫連接connect和關閉數據庫連接close

創建數據庫連接的三種方式:

方法一:用戶名、密碼和監聽分開寫

import cx_Oracle

db=cx_Oracle.connect('username/password@host/orcl')

db.close()

 

方法二:用戶名、密碼和監聽寫在一起

import cx_Oracle

db=cx_Oracle.connect('username','password','host/orcl')

db.close()

 

方法三:配置監聽並連接

import cx_Oracle

tns=cx_Oracle.makedsn('host',1521,'orcl')

db=cx_Oracle.connect('username','password',tns)

db.close()

python鏈接oracle數據庫時報64-bit Oracle Client library cannot be loaded: "The specified module could not be found"錯誤

在使用pycharm對遠程oracle數據庫進行訪問時(本地未安裝oracle),會出現64-bit Oracle Client library cannot be loaded: "The specified module could not be found"的錯誤。
(1)首先要做的是按照網上有的下載對應版本的instantclient
下載地址:http://www.oracle.com/technetwork/database/database-technologies/instant-client/overview/index.html
需要64位的就下載64位的,需要32位的就下載32位的,這次錯誤提示是需要64位的,所以我下載的是64位的。
(2)將解壓后的instantclient路徑添加到環境變量PATH中**
在這里插入圖片描述
到文件夾即可
(3)在文件夾中創建名為‘ tnsnames.ora ’的文件,文件內容:
orcl =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = IP地址)(PORT = 1521))
)
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
IP地址和SERVICE_NAME可根據需要更改
(4)將文件夾下的oci.dll, oraocci12.dll,oraociei12.dll 拷貝到python安裝目錄下的lib/site-packages中**
(5)重啟pycharm

重點來了,如果還報錯,那就是你沒有安裝正確的vc++庫。

檢測方式是打開你的instantclient_xx_x,找到genezi.exe,點開看看是不是報"缺少msvcr120.dll"
如果是那你就得去下載vc++庫了
下載地址是:
https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads#bookmark-vs2013
注意oracle18和orcale12.2版本的下載vs2013!!!
然后重啟pycharm,ok,收工。

cx_Oracle錯誤:Unable to acquire Oracle environment handle

錯誤表現:
cx_Oracle連接Oracle數據庫的時候報錯:
cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle

解決辦法:將instantclient目錄下的所有*.dll文件拷貝到Python27\Lib\site-packages目錄下,問題解決

SQLAlchemy Oracle 的中文問題

你需要設置 NLS_LANG 環境變量,否則你讀取出來的中文可能是亂碼,或者當 insert 的數據有中文時會導致 Unicode 編碼錯誤。

你可以在 Python 代碼中這么設置環境變量

# 設置編碼,否則: # 1. Oracle 查詢出來的中文是亂碼 # 2. 插入數據時有中文,會導致 # UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-7: ordinal not in range(128) os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

No module named cx_Oracle:
import cx_Oracle ImportError: No module named cx_Oracle

如果安裝的 python 64 位,需要把cx_Oracle文件復制到 /usr/lib64/python2.7/site-packages/ 目錄下

cd /usr/lib/python2.7/site-packages/ cp cx_Oracle.so /usr/lib64/python2.7/site-packages/cx_Oracle.so cp cx_Oracle-5.1.2-py2.7.egg-info /usr/lib64/python2.7/site-packages/cx_Oracle-5.1.2-py2.7.egg-info

還有如下方法:

1、復制oci.dll到$python_home (比如c:/python26)解決的

2、復制oci.dll到$python_home和C:\Python33\Lib\site-packages 下解決的

3、老外是重裝解決的。

I was able to solve this problem with the following steps:

Download instantclient-basic-win32-10.2.0.5 from Oracle Website

unzipped the into my c:\ with the name oraclient

Created the directory structure C:\oraclient\network\admin to add the TNSNAMES.ORA

Added the TNS_ADMIN env var pointing to C:\oraclient\network\admin

Added the ORACLE_HOME env var pointing to C:\oraclient\

http://stackoverflow.com/questions/13708998/cx-oracle-and-python-2-7

 

下載一個

instantclient-basic-win32-10.2.0.4.zip
然后復制到C:\Python33\Lib\site-packages搞定。

 

  首先安裝配置時,必須把握一個點,就是版本一致!包括:系統版本,python版本,oracle客戶端的版本,cx_Oracle的版本,然后安裝配置就容易了!

  因為我的系統是win7 64位,python版本也是64位的,所以下載安裝的Oracle Client 也是64位 10g的,相應的cx_Oracle 也要是64位10g的,當然也要注意python的版    本python2.X還是python3.X,也要下相應的版本的

     1、oracle client 下載地址:http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html

     把下載的文件解壓到自己想要放的路徑下,我的是Q:\OracleClient,

  然后是配置環境變量:右鍵計算機——屬性——高級系統設置——環境變量——系統變量——新建

  變量:ORACLE_HOME  值:Q:\OracleClient

  變量:TNS_ADMIN       值:Q:\OracleClient

  編輯path用';'隔開加一個  Q:\OracleClient

 

  2、cx_Oracle就可以在PyPI中下載,打開PyPI的網址https://pypi.python.org/pypi,在里面搜索cx_Oracle,找到相應的版本下載,下載完成后安裝就可以了

           也可以在 https://sourceforge.net/projects/cx-oracle/files/ 下下載cx_Oracle

  3、遇到的一些問題,及解決方法

  "cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle"  

      或者是  "ImportError: DLL load failed: 找不到指定的程序"

  或者是  "import cx_Oracle,ImportError: DLL load failed: 找不到指定的模塊"

  ---解決方法:把下載解壓的oracle client 中的ico.dll,復制到python的安裝目錄下即可,網上看到有些人的解決方法是放到Python27\Lib\site-packages下

    

     "cx_Oracle.DatabaseError: ORA-12170: TNS"   --解決方法:檢查自己的網絡、監聽、tnsname.ora都行

     "cx_Oracle ORA-24315: 非法的屬性類型"   ----出現該錯誤的原因是因為版本不兼容,檢查一下環境,如果oracle client是10g的,但安裝的cx_oracle是for 11g的話就會報這個錯,下載cx_oracle是for 10g的安裝即可

UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position ... 問題解決辦法

目標文件的編碼是導致標題所指問題的罪魁禍首
f = open("out.html","w")

,在windows下面,新文件的默認編碼是gbk,這樣的話,python解釋器會用gbk編碼去解析我們的網絡數據流txt,然而txt此時已經是decode過的unicode編碼,這樣的話就會導致解析不了,出現上述問題。 解決的辦法就是,改變目標文件的編碼:

f = open("out.html","w",encoding='utf-8')
問題解決。

1. cx_Oracle
cx_Oracle模塊是Python連接Oracle數據庫的模塊,在Python中,如果要連接Oracle,必須先安裝cx_Oracle模塊。
cx_Oracle的下載地址:https://pypi.python.org/pypi/cx_Oracle/
選擇和操作系統、Python版本一致的安裝包進行安裝。當然為了省事兒,你也可以直接使用pip命令來安裝cx_Oracle。

pip install cx_Oracle

安裝完成后,在交互模式下輸入import cx_Oracle,不報錯,說明安裝成功。

2. 連接Oracle數據庫
方法一:用戶名、密碼、監聽分開寫

import cx_Oracle
db=cx_Oracle.connect('username','password','host:port/sid')


方法二:用戶名、密碼、監聽寫一起

import cx_Oracle
db=cx_Oracle.connect('username/password@host:port/sid')

方法三:先配置監聽,后連接

import cx_Oracle
tnsname = cx_Oracle.makedsn('host', port,'sid')
db = cx_Oracle.connect('username','password',tnsname)

說明:代碼中username、password、host、port、sid換成實際數據庫的用戶名、密碼、主機名或主機IP、數據庫實例名。

3. 創建游標
cx_Oracle中,對於數據庫的增刪改查操作需要通過游標來進行,游標的創建語句如下:

cur=db.cursor()

4. 執行sql語句
Sql語句書寫:不需要從外部傳入參數,可以直接書寫sql語句,然后使用execute執行sql即可;如果需要從外部傳入參數,在需要傳入參數的地方使用變量,並在變量前加“:”,然后通過prepare加載sql語句。

cur.prepare:如果執行的sql語句需要傳外部參數,可以先用這個函數加載sql語句,然后再通過execute或executemany加參數執行。
cur.execute:執行單條sql語句。
cur.executemany:執行多條sql語句。
關於execute需要說明的是如果執行的sql語句不需要從外部傳入參數,那么可以跳過prepare,直接將sql語句作為execute的第一個參數來執行sql。

db.commit():執行提交操作,增、刪、改后需要使用。
cur.fetchall:在查詢之后使用,獲取所有查詢到的結果記錄。
cur.fetchone:在查詢之后使用,獲取一條查詢到的結果記錄。
關於fetchall和fetchone需要說明的是查詢到的記錄一旦被提取,就不能再次被提取,不管是用fetchall提取還是使用fetchone提取。

res = cur.fetchall()[0][0].read();

fetchall和fetchone返回的是元組,加上[][],可以直接取到值。

for result in cur:  #循環從游標獲取每一行並輸出該行。
    print result
寫完游標可以去循環游標讓它輸出結果。
 

查詢:
需要外部參數:

>>> cur.prepare('select * from t_emp a where a.empid=:id')
>>> cur.execute(None,{'id':id})
<cx_Oracle.Cursor on <cx_Oracle.Connection to cs@192.168.1.226:1521/db_emp>>
>>> cur.fetchall()

不需要外部參數:

>>> cur.execute("select e.empid,e.empname from t_emp e")
<cx_Oracle.Cursor on <cx_Oracle.Connection to cs@192.168.102.219:1521/t45>>
>>> cur.fetchone()
(1, '張三')
>>> cur.fetchall()
[(2, '李四'), (3, '王五'), (4, '沈六'), (5, '田七'), (6, '鳳九')]

增加、刪除、修改:

單條增加:

>>> sql="insert into t_emp(empid,empname) values (:empid,:empname)"
>>> cur.prepare(sql)
>>> cur.execute(None,{'empname':'李紳','empid':7})
>>> db.commit()

多條增加:

>>> sql="insert into t_emp(empid,empname) values (:empid,:empname)"
>>> cur.prepare(sql)
>>> cur.executemany(None,[{'empname':'趙青','empid':8},{'empname':'蕭遠','empid':9}])
>>> db.commit()

單條修改:

>>> sql="update t_emp a set a.empname='清月' where a.empid=:empid"
>>> cur.prepare(sql)
>>> cur.execute(None,{empid:"4"})
>>> db.commit()

多條修改:

>>> sql="update t_emp a set a.empname=:empnamewhere a.empid=:empid"
>>> cur.prepare(sql)
>>> cur.executemany(None,[{'empid':"5","empname":"明月"},{'empid':"6","empname":"樂天"}])
>>> db.commit()

刪除:

>>> cur.execute('delete from t_emp a where a.empid in (3,4,5,6)')
>>> db.commit()

5. 關閉游標
sql語句執行結束,不再使用時,應關閉游標,關閉游標的語句為:

cur.close()

6. 關閉數據庫
數據庫操作結束后應及時釋放連接,關閉數據庫連接的語句為:

db.close()

7. 我寫的一個Oracle數據庫操作類
cx_Oracle是Python的Oracle操作的模塊,在使用時導入就能使用,但是因為數據庫使用時涉及連接、操作、提交、關閉連接等一系列操作,不可能每次使用時都把這些操作用代碼寫一遍,所以我把這些操作放到一個類里,在實際使用時來調用這個類就行了。

#coding=utf-8
import cx_Oracle
class OpOracle():
    def __init__(self,ora_username,ora_password,ora_host,ora_port,ora_sid):
        '''初始化Oracle連接'''
        self.db=cx_Oracle.connect(ora_username,ora_password,ora_host+':'+ora_port+'/'+ora_sid)
        self.cur=self.db.cursor()
    def Ora_Select(self,strSql):
        '''執行strSql語句進行查詢'''
        self.cur.execute(strSql)
        return self.cur.fetchall()
    def Ora_IUD_Single(self,strSql):
        '''執行strSql語句進行增加、刪除、修改操作'''
        self.cur.execute(strSql)
        self.db.commit()
    def Ora_IUD_Multi(self,strSql,List):
        '''執行strSql語句進行增加、刪除、修改操作,對應參數使用List中的數據'''
        self.cur.prepare(strSql)
        self.cur.executemany(None,List)
        self.db.commit()
    def Ora_Cur_Close(self):
        '''關閉游標'''
        self.cur.close()
    def Ora_db_Close(self):
        '''關閉Oracle數據庫連接'''
        self.db.close()

 

我把這段代碼保存在OpOracle.py文件中,使用時直接導入這個文件即可。如:

from OpOracle import OpOracle
ora=OpOracle('cs','ceshi','192.168.1.226','1521','db_emp')
l_emp=ora.Ora_Select('select * from t_emp')    #查詢t_emp表的數據並保存到l_emp列表中
ora.Ora_IUD_Single('delete from t_emp a where a.empid=1')  #刪除empid為1的記錄
ora.Ora_Cur_Close()
ora.Ora_db_Close()     #最后記得關閉游標和數據庫連接

---------------------
后面代碼操作來自:
原文:https://blog.csdn.net/xinyuzxx/article/details/81703625

 


免責聲明!

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



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