1. 程式人生 > 實用技巧 >python操作Oracle--cx_Oracle模組

python操作Oracle--cx_Oracle模組

第一part:cx_Oracle模組的安裝


第一種安裝方式通過命令列: pip install cx_Oracle

第二種方式通過pycharm--project--settings--project interpreter中搜索cx_Oracle進行安裝


第二part:安裝Oracle版本對應的客戶端,並配置到path變數中


python連線Oracle資料庫前,必須要安裝Oracle版本對應的客戶端,否則python對Oracle操作時會拋異常。

下載官網:https://oracle.github.io/odpi/doc/installation.html#windows,必須與Oracle版本對應的client

1.下載成功之後,解壓到一個新的資料夾中:

2.並將其配置到path變數中:

3.重啟pycharm即可。


第三part:python操作cx_Oracle模組---連線Oracle的方式


第一種方式:普通使用者

如果埠號預設1521可以省略
#匯入模組
import cx_Oracle
get_conn1 = cx_Oracle.connect('scott','tiger','localhost:1521/orcl')


第二種方式:普通使用者
#匯入模組
import cx_Oracle
get_conn2 = cx_Oracle.connect('scott/tiger@localhost:1521/orcl')


第三種方式:系統管理員
#匯入模組
import cx_Oracle
get_conn3 = cx_Oracle.connect('sys/123456@localhost:1521/orcl',mode=cx_Oracle.SYSDBA)


第四種方式:dsn_tns
#匯入模組
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('localhost', 1521, 'orcl')
get_conn4 = cx_Oracle.connect('scott', 'tiger', dsn_tns)


第四part:python對Oracle資料庫的新增,修改,刪除,查詢以及回滾資料


python對Oracle資料庫的新增,修改,刪除,查詢以及回滾資料與python對mysql資料庫的操作是一致的,詳細操作可見上一篇文章:https://www.cnblogs.com/smilecindy/p/13777779.html

在此處只簡單的介紹一下查詢操作:

#1:匯入cx_Oracle模組
import cx_Oracle
#2,連線orcle資料庫,使用connect函式,其中包含使用者名稱,密碼,資料庫服務地址:埠號/orcl
get_connect=cx_Oracle.connect('scott','123456','localhost:1521/orcl')
#3:建立遊標,用於獲取結果集
get_cursor=get_connect.cursor()
#4:定義一條sql語句
str_sql="select * from emp where empno='7369'"
# 5:使用遊標進行執行sql
get_cursor.execute(str_sql)
#6.獲取結果值,fetchall表示查詢所有的記錄
result=get_cursor.fetchall()
print(result)
#7:關閉遊標連線
get_cursor.close()
#8:關閉資料庫連線
get_connect.close()

執行之後,結果如下: