Python之cx_Oracle、psycopg2模块处理数据库数据

冷不防 2022-04-13 05:40 416阅读 0赞
  1. # coding=utf-8
  2. import sys
  3. import cx_Oracle
  4. import psycopg2
  5. import psycopg2.extras
  6. import datetime
  7. conn_oracle = cx_Oracle.connect("")
  8. print("Opened oracle successfully")
  9. cur_oracle = conn_oracle.cursor()
  10. conn_pg = psycopg2.connect(database='amdb', user='', password='', host='',
  11. port='')
  12. print("Opened pg successfully")
  13. # cur_pg = conn_pg.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
  14. cur_pg = conn_pg.cursor()
  15. def process_data(rows):
  16. rows = [('10.131.178.78', 'T10103', 'E4D058D6-E5CB-40FA-9A9D-04DA1D6DEF22-00064'),
  17. ('10.131.178.77', 'T60302', 'E4D058D6-E5CB-40FA-9A9D-04DA1D6DEF22-00055')]
  18. for row in rows:
  19. #数据处理关键代码
  20. ip_list.append("""\'%s\'""" % str(row[0]))
  21. pg_sql = "select resourceid from am_managedobject where resourcename in (%s)" % (",".join(ip_list))
  22. return pg_sql
  23. def read_COLLECT(id_list):
  24. """读取COLLECT表"""
  25. ids = (",".join(id_list))
  26. collect_config_sql = "SELECT COLL_FUNC from COLLECT where AGENT_CODE='APM_PG'"
  27. collect_config = exec_oracle_sql(collect_config_sql)
  28. result_list = []
  29. for cfg in collect_config:
  30. #数据库的COLL_FUNC 形式为select resourceid from am_managedobject where resourcename in (%s)
  31. result = exec_pg_sql(cfg[0] % ids)
  32. result_list.append(result)
  33. return result_list
  34. def get_some_info(new_dict, attr_code, result, perf_attr):
  35. """获取操作系统信息,插入数据库"""
  36. print(new_dict, attr_code, result, perf_attr)
  37. #Oracle数据库处理日期方法
  38. dt = datetime.datetime.now()
  39. perf_attr_sql = ""
  40. for resids in result:
  41. for resid in resids:
  42. for key in new_dict.keys():
  43. if int(key) == resid[0]:
  44. params = {'devtype': new_dict[key][1], 'devid': new_dict[key][2], 'attrcode': attr_code,
  45. 'result': resid[1], 'dt': dt}
  46. if perf_attr == 2:
  47. try:
  48. cur_oracle.execute(
  49. 'insert into ATTR_RESULT values(:devtype,:devid,:attrcode,:result,:dt)',
  50. params)
  51. print("配置数据插入成功!成功数据为:%s" % params)
  52. except cx_Oracle.IntegrityError as e:
  53. print("配置数据插入失败,重复插入!失败数据为:%s" % params)
  54. elif perf_attr == 1:
  55. try:
  56. cur_oracle.execute(
  57. 'insert into PERF_RESULT values(:devtype,:devid,:attrcode,:result,:dt)',
  58. params)
  59. print("性能数据插入成功!成功数据为:%s" % params)
  60. except cx_Oracle.IntegrityError as e:
  61. print("性能数据插入失败,重复插入!失败数据为:%s" % params)

发表评论

表情:
评论列表 (有 0 条评论,416人围观)

还没有评论,来说两句吧...

相关阅读

    相关 pythonpanda模块2

    上一节中说了Python的基础数据结构,这一节我来总结一下我所学到的pandas的部分知识点: Pandas 是 Python 的核心数据分析支持库,提供了快速、灵活、明确的

    相关 Python数据处理模块Pandas

    Pandas使用一个二维的数据结构DataFrame来表示表格式的数据,相比较于Numpy,Pandas可以存储混合的数据结构,同时使用NaN来表示缺失的数据,而不用像Nump