oracle.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. # 处理可能存在的LOB对象,确保可以JSON序列化
  45. for item in list:
  46. for key, value in item.items():
  47. # 如果值是LOB对象,尝试读取其内容
  48. if hasattr(value, 'read'):
  49. try:
  50. item[key] = value.read()
  51. except:
  52. item[key] = str(value)
  53. jobj = json.loads(json.dumps(list, ensure_ascii=False))
  54. return jobj
  55. def insert(self, sql, dict = None):
  56. """查询数据
  57. :param sql:SQL语句 ==> insert into 表(字段1,字段2) values(:字段1,:字段2)
  58. :param dict:值字典 ==> {"字段1":"abc", "字段2":"abc"}
  59. """
  60. if dict == None:
  61. self.cursor.execute(sql)
  62. else:
  63. self.cursor.execute(sql, dict)
  64. self.commit()