oracle.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # -*- coding: utf-8 -*-
  2. #设置语言环境
  3. import os
  4. import sys
  5. import json
  6. import log
  7. reload(sys)
  8. sys.setdefaultencoding('utf-8')
  9. os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
  10. import cx_Oracle
  11. class Oracle:
  12. def __init__(self, conn):
  13. """Oracle
  14. C:\Python27\ArcGISx6410.8\Scripts
  15. pip install cx-Oracle==7.3.0
  16. :param conn:数据库连接字符串('user/password@127.0.0.1/orcl')
  17. """
  18. self._conn = cx_Oracle.connect(conn, encoding="UTF-8", nencoding="UTF-8")
  19. self.cursor = self._conn.cursor() #游标
  20. def commit(self):
  21. self._conn.commit()
  22. def close(self):
  23. try:
  24. if hasattr(self,'cursor'):
  25. self.cursor.close()
  26. if hasattr(self,'_conn'):
  27. self._conn.close()
  28. except:
  29. msg = str(sys.exc_info()).decode('string-escape')
  30. log.error(msg)
  31. def __del__(self):
  32. self.close()
  33. def query(self, sql):
  34. """查询所有数据
  35. :param sql:SQL语句
  36. """
  37. self.cursor.execute(sql)
  38. ds = self.cursor.fetchall()
  39. cols = [d[0] for d in self.cursor.description]
  40. list = []
  41. for row in ds:
  42. b = dict(zip(cols, row))
  43. list.append(b)
  44. jobj = json.loads(json.dumps(list, ensure_ascii=False))
  45. return jobj
  46. def insert(self, sql, dict = None):
  47. """查询数据
  48. :param sql:SQL语句 ==> insert into 表(字段1,字段2) values(:字段1,:字段2)
  49. :param dict:值字典 ==> {"字段1":"abc", "字段2":"abc"}
  50. """
  51. if dict == None:
  52. self.cursor.execute(sql)
  53. else:
  54. self.cursor.execute(sql, dict)
  55. self.commit()