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.version10.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.dsnlocalhost:1521/XE2. 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.“。
Executecx_Oracle.Cursor.execute(statement,[parameters], **keyword_parameters)
該方法能接收單個參數(shù)SQL,直接操作數(shù)據(jù)庫,也可以通過綁定變量執(zhí)行動態(tài)SQL,parames或keyworparameters可以是字典、序列或一組關(guān)鍵字參數(shù)。
cx_Oracle.Cursor.executemany(statement,parameters)
特別有用的批量插入,避免一次只能插入一條;
Fetch(optional)
僅用于查詢,因為DDL和DCL語句沒有返回結(jié)果。如果cursor沒有執(zhí)行查詢,會拋出InterfaceError異常。
cx_Oracle.Cursor.fetchall()
獲取所有結(jié)果集,返回元祖列表,如果沒有有效行,返回空列表。
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_Oracleclass 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)容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答
圖片精選