Guest User

Untitled

a guest
Feb 18th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. class OracleCursor:
  2. """游标类"""
  3.  
  4. def __init__(self, cursor, logger, dict_result):
  5. self.cursor = cursor
  6. self.logger = logger
  7. self.dict_result = dict_result
  8.  
  9. def _dict_result(self, cursor):
  10. cols = [d[0].lower() for d in cursor.description]
  11. def row_factory(*args):
  12. return dict(zip(cols, args))
  13. return row_factory
  14.  
  15. def execute(self, sql, params=None):
  16. if params:
  17. self.cursor.execute(sql, params)
  18. else:
  19. self.cursor.execute(sql)
  20.  
  21. def query(self, sql, params=None, with_description=False):
  22. if params:
  23. self.cursor.execute(sql, params)
  24. else:
  25. self.cursor.execute(sql)
  26. if self.dict_result:
  27. self.cursor.rowfactory = self._dict_result(self.cursor)
  28. rows = self.cursor.fetchall()
  29. if with_description:
  30. res = rows, self.cursor.description
  31. else:
  32. res = rows
  33. return res
  34.  
  35.  
  36. class OracleInstance:
  37. """实例类"""
  38.  
  39. def __init__(self, username, password, host, port, sid,
  40. charset='utf8',dict_result=False,logger=None):
  41. self.username = username
  42. self.password = password
  43. self.host = host
  44. self.port = port
  45. self.sid = sid
  46. self.charset = charset
  47. self.dict_result = dict_result
  48. if logger is None:
  49. logger=logging.getLogger(__name__)
  50. self.logger = logger
  51.  
  52. def __enter__(self):
  53. dsn_tns = cx_Oracle.makedsn(self.host, self.port, self.sid)
  54. self.con = cx_Oracle.connect(self.username, self.password, dsn_tns)
  55. self.cursor = self.con.cursor()
  56. return OracleCursor(self.cursor, self.logger, self.dict_result)
  57.  
  58. def __exit__(self, exc_type, exc_val, exc_tb):
  59. self.cursor.execute("commit")
  60. self.cursor.close()
  61. self.con.close()
Add Comment
Please, Sign In to add comment