標籤:版本 exec rac 普通使用者 comm com tar let imp
python可通過使用cx_Oracle模組對Oracle資料庫進行操作。
首先,需要下載cx_Oracle模組,:https://pypi.python.org/pypi/cx_Oracle/6.0rc1
下載的時候注意版本,對照你所使用的Python版本和位元。
我所使用的是Python3.6,所以下載的版本是:cx_Oracle-6.0rc1-cp36-cp36m-win_amd64.whl
然後安裝即可:
python -m pip install cx_Oracle-6.0rc1-cp36-cp36m-win_amd64.whl
代碼舉例:
#用途:操作oracle資料庫demoimport cx_Oracleuser = "yzwxceshi"passwd = "yzwxceshi"listener = ‘192.168.20.191:1521/orcl‘conn = cx_Oracle.connect(user, passwd, listener)print(conn)cursor = conn.cursor()sql = "select * from T_MSIS_SM_ROLE"#一次取一條資料,row為元組資料cursor.execute(sql)while (1): row = cursor.fetchone() if row == None: break print(row)print("--------------------------------------")#一次取所有資料,rows為元組列表資料cursor.execute(sql)rows = cursor.fetchall()for row in rows: print(row)#支援對資料庫的插入、更新和刪除操作。輸入操作SQL,執行無返回。def other_operation(sql): cursor.execute(sql) conn.commit() print(sql)cursor.close()conn.close()
封裝成類代碼舉例:
#oracle操作類import cx_Oracleclass Oracle_Class: user = "yzwxceshi" passwd = "yzwxceshi" listener = ‘192.168.20.191:1521/orcl‘ conn = cx_Oracle.connect(user, passwd, listener) cursor = conn.cursor() # 查詢操作:一次性取所有資料。輸入查詢SQL,返回結果元組列表。 def querydata(self, sql): list_result = [] self.cursor.execute(sql) rows = self.cursor.fetchall() for row in rows: list_result.append(row) return list_result # 支援對資料庫的插入、更新和刪除操作。輸入操作SQL,無返回。 def other_operation(self, sql): self.cursor.execute(sql) self.conn.commit() print(sql) # 關閉串連,釋放資源 def close_all(self): self.cursor.close() self.conn.close()
調用代碼:
#用於測試資料庫操作from oracle_class import Oracle_Classselect_sql = "select ROLE_NAME from T_MSIS_SM_ROLE"insert_sql = "insert into T_MSIS_SM_ROLE values (14, ‘role_name‘, ‘普通使用者‘)"update_sql = "update T_MSIS_SM_ROLE set ROLE_DESC = ‘測試使用者‘ where ROLE_ID = 16"delete_sql = "delete from T_MSIS_SM_ROLE where ROLE_ID = 15"oracle_obj = Oracle_Class()oracle_obj.other_operation(delete_sql)list = oracle_obj.querydata(select_sql)print(list)oracle_obj.close_all()
python之Oracle操作(cx_Oracle)