2.PYTHON连接oracle数据库,封装了方法
#encoding:utf-8 import cx_Oracle #name='admin' #password='admin' #tnsname='admin' #创建我的封装数据库类 class MyOracle(): #初始化数据库参数:使用者,密码,数据库 def __init__(self,name,password,tnsname): self.name = name; self.password = password; self.tnsname = tnsname; self.conn = None self._myconnect() print("初始化成功") return None #创建数据库连接 def _myconnect(self): if not self.conn: try: self.conn = cx_Oracle.connect(self.name,self.password,self.tnsname) print('连接数据库成功') except Exception as e: print(e) else: pass #程序运行完毕,自动关闭连接 def __del__(self): if self.conn: self.conn.close() self.conn = None #建立游标指针 def mycursor(self): try: cur = self.conn.cursor() if cur: print("建立cursor指针OK") return cur else: return None except Exception as e: self.myconnclose() print(e) #查询数据库数据 def myquery(self,sql,cur): try: cur.execute(sql) row=cur.fetchall() tabletopname = cur.description print("查询数据成功") return tabletopname,row except Exception as e: print(e) #塞入数据 def insertsql(self,sql,cur,data): try: if sql.upper().startswith("INSERT"): cur.execute(sql,data) self.conn.commit() print("插入资料OK") self.mycurclose(cur) except Exception as e: self.conn.rollback() print("插入资料失败") print(e) #打印数据 def myprint(self,row): print(row) for r in row: print(r) print('打印数据成功') #关闭光标,关闭数据库连裤 def mycurclose(self,cur): try: if cur: cur.close() print('关闭游标跟数据库连接成功') except Exception as e: print(e) def myconnclose(self): if self.conn: self.conn.close() self.conn = None