python操作oracle的完整教程分享
1. 連接對象
操作數(shù)據(jù)庫之前,首先要建立數(shù)據(jù)庫連接。
有下面幾個方法進行連接。
>>>import cx_Oracle >>>db = cx_Oracle.connect('hr', 'hrpwd', 'localhost:1521/XE') >>>db1 = cx_Oracle.connect('hr/hrpwd@localhost:1521/XE') >>>dsn_tns = cx_Oracle.makedsn('localhost', 1521, 'XE') >>>print dsn_tns >>>print db.version 10.2.0.1.0 >>> versioning = db.version.split('.') >>> print versioning ['10', '2', '0', '1', '0'] >>> if versioning[0]=='10': ... print "Running 10g" ... elif versioning[0]=='9': ... print "Running 9i" ... Running 10g >>> print db.dsn localhost:1521/XE
2. cursor對象
使用數(shù)據(jù)庫連接對象的cursor()方法,你可以定義任意數(shù)量的cursor對象,簡單的程序可能使用一個cursor,并重復使用了,但大型項目會使用多個不同的cursor。
>>>cursor= db.cursor()
應用程序邏輯通常需要清楚的區(qū)分處理數(shù)據(jù)操作的每個階段。這將幫助更好的理解性能瓶頸和代碼優(yōu)化。
這些步驟有:
parse(optional)
無需調(diào)用該方法,因為執(zhí)行階段會自動先執(zhí)行,用于檢查sql語句是否正確,當有錯誤時,拋出DatabaseError異常及相應的錯誤信息。如:‘'ORA-00900:invalid SQL statement.“。
Execute cx_Oracle.Cursor.execute( statement,[parameters], **keyword_parameters)
該方法能接收單個參數(shù)SQL,直接操作數(shù)據(jù)庫,也可以通過綁定變量執(zhí)行動態(tài)SQL,parames或keyworparameters可以是字典、序列或一組關鍵字參數(shù)。
cx_Oracle.Cursor.executemany(statement,parameters)
特別有用的批量插入,避免一次只能插入一條;
Fetch(optional)
僅用于查詢,因為DDL和DCL語句沒有返回結果。如果cursor沒有執(zhí)行查詢,會拋出InterfaceError異常。
cx_Oracle.Cursor.fetchall()
獲取所有結果集,返回元祖列表,如果沒有有效行,返回空列表。
cx_Oracle.Cursor.fetchmany([rows_no])
從數(shù)據(jù)庫中取下一個rows_no數(shù)據(jù)
cx_Oracle.Cursor.fetchone()
從數(shù)據(jù)庫中取單個元祖,如果沒有有效數(shù)據(jù)返回none。
3. 綁定變量
綁定變量查詢可以提高效率,避免不必要的編譯;參數(shù)可以是名稱參數(shù)或位置參數(shù),盡量使用名稱綁定。
>>>named_params = {'dept_id':50, 'sal':1000} >>>query1 = cursor.execute('SELECT * FROM employees WHERE department_id=:dept_idAND salary>:sal', named_params) >>> query2 = cursor.execute('SELECT * FROM employees WHERE department_id=:dept_idAND salary>:sal', dept_id=50, sal=1000) Whenusing named bind variables you can check the currently assigned ones using thebindnames() method of the cursor: >>> printcursor.bindnames() ['DEPT_ID', 'SAL']
4. 批量插入
大量插入插入操作,可以使用python的批量插入功能,無需多次單獨調(diào)用insert,這樣可以提升性能。參考后面示例代碼。
5. 示例代碼
''' Created on 2016年7月7日 @author: Tommy ''' import cx_Oracle class Oracle(object): """ oracle db operator """ def __init__(self,userName,password,host,instance): self._conn = cx_Oracle.connect("%s/%s@%s/%s" % (userName,password,host,instance)) self.cursor = self._conn.cursor() def queryTitle(self,sql,nameParams={}): if len(nameParams) > 0 : self.cursor.execute(sql,nameParams) else: self.cursor.execute(sql) colNames = [] for i in range(0,len(self.cursor.description)): colNames.append(self.cursor.description[i][0]) return colNames # query methods def queryAll(self,sql): self.cursor.execute(sql) return self.cursor.fetchall() def queryOne(self,sql): self.cursor.execute(sql) return self.cursor.fetchone() def queryBy(self,sql,nameParams={}): if len(nameParams) > 0 : self.cursor.execute(sql,nameParams) else: self.cursor.execute(sql) return self.cursor.fetchall() def insertBatch(self,sql,nameParams=[]): """batch insert much rows one time,use location parameter""" self.cursor.prepare(sql) self.cursor.executemany(None, nameParams) self.commit() def commit(self): self._conn.commit() def __del__(self): if hasattr(self,'cursor'): self.cursor.close() if hasattr(self,'_conn'): self._conn.close() def test1(): # sql = """select user_name,user_real_name,to_char(create_date,'yyyy-mm-dd') create_date from sys_user where id = '10000' """ sql = """select user_name,user_real_name,to_char(create_date,'yyyy-mm-dd') create_date from sys_user where id =: id """ oraDb = Oracle('test','java','192.168.0.192','orcl') fields = oraDb.queryTitle(sql, {'id':'10000'}) print(fields) print(oraDb.queryBy(sql, {'id':'10000'})) def test2(): oraDb = Oracle('test','java','192.168.0.192','orcl') cursor = oraDb.cursor create_table = """ CREATE TABLE python_modules ( module_name VARCHAR2(50) NOT NULL, file_path VARCHAR2(300) NOT NULL ) """ from sys import modules cursor.execute(create_table) M = [] for m_name, m_info in modules.items(): try: M.append((m_name, m_info.__file__)) except AttributeError: pass sql = "INSERT INTO python_modules(module_name, file_path) VALUES (:1, :2)" oraDb.insertBatch(sql,M) cursor.execute("SELECT COUNT(*) FROM python_modules") print(cursor.fetchone()) print('insert batch ok.') cursor.execute("DROP TABLE python_modules PURGE") test2()
以上這篇python操作oracle的完整教程分享就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- python實現(xiàn)自動化報表功能(Oracle/plsql/Excel/多線程)
- python使用 cx_Oracle 模塊進行查詢操作示例
- 使用Python腳本zabbix自定義key監(jiān)控oracle連接狀態(tài)
- Python如何應用cx_Oracle獲取oracle中的clob字段問題
- 解決python通過cx_Oracle模塊連接Oracle亂碼的問題
- 解決python3捕獲cx_oracle拋出的異常錯誤問題
- Python3連接SQLServer、Oracle、MySql的方法
- Python3.6連接Oracle數(shù)據(jù)庫的方法詳解
- Python讀寫及備份oracle數(shù)據(jù)庫操作示例
- Python操作Oracle數(shù)據(jù)庫的簡單方法和封裝類實例
- Python使用cx_Oracle模塊操作Oracle數(shù)據(jù)庫詳解
- python鏈接oracle數(shù)據(jù)庫以及數(shù)據(jù)庫的增刪改查實例
- python cx_Oracle的基礎使用方法(連接和增刪改查)
- Python使用cx_Oracle調(diào)用Oracle存儲過程的方法示例
- Python編程實戰(zhàn)之Oracle數(shù)據(jù)庫操作示例
- windows下python連接oracle數(shù)據(jù)庫
- python安裝oracle擴展及數(shù)據(jù)庫連接方法
- Python連接Oracle之環(huán)境配置、實例代碼及報錯解決方法詳解
相關文章
Python實現(xiàn)輕松識別數(shù)百個快遞單號
當我們要寄出很多快遞時,為了及時反饋物流信息,需要盡快將快遞單號提取出來。這時用手動去識別真的太麻煩,所以本文將用Python實現(xiàn)輕松識別數(shù)百個快遞單號,需要的可以參考一下2022-06-06python實現(xiàn)將JPG、BMP圖片轉(zhuǎn)化為bgr
這篇文章主要介紹了python實現(xiàn)將JPG、BMP圖片轉(zhuǎn)化為bgr方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03Pycharm+Python工程,引用子模塊的實現(xiàn)
這篇文章主要介紹了Pycharm+Python工程,引用子模塊的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Python實現(xiàn)解析命令行參數(shù)的常見方法總結
除ide的執(zhí)行方式外,命令行的方式執(zhí)行Python腳本是參數(shù)化程序執(zhí)行的一種常見且簡單的方法。本文總結了三個常見的獲取和解析命令行參數(shù)的方法,需要的可以參考一下2022-10-10