Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. " Pythonからmysqlへの接続ラッパー
  4. """
  5. import sys
  6. import os
  7.  
  8. import pymysql.cursors
  9.  
  10. ABS_DIR_PATH = os.path.abspath(os.path.dirname(__file__))
  11. sys.path.append(ABS_DIR_PATH + '/../') # for const
  12. # sys.path.append(ABS_DIR_PATH + '/lib')
  13.  
  14. import constant as const
  15.  
  16. class DB:
  17.  
  18. def __init__(self):
  19. pass
  20.  
  21. @staticmethod
  22. def get_connect():
  23. try:
  24. conn = pymysql.connect(
  25. host=const.RDS_HOST,
  26. port=const.DB_PORT,
  27. db=const.DB_NAME,
  28. user=const.DB_USERNAME,
  29. password=const.DB_PASSWORD)
  30. cur = conn.cursor()
  31. # cur.execute("SET search_path = " + const.DB_SET_SEARCH_PATH)
  32. print "connection!!"
  33. return conn
  34.  
  35. except Exception as e:
  36. print "DBコネクションエラー"
  37.  
  38.  
  39. # INSERT
  40. # UPDATE
  41. @classmethod
  42. def execute(cls, query):
  43. try:
  44. with cls.get_connect() as con:
  45. with con.cursor() as cur:
  46. cur.execute(query)
  47. con.commit()
  48.  
  49. # 重複する場合を例外処理
  50. except psycopg2.IntegrityError as e:
  51. pass
  52.  
  53. except Exception as e:
  54. raise Exception('クエリ実行失敗 [%(message)s] ' % {'message': str(e.message)})
  55.  
  56.  
  57.  
  58. def conn(self):
  59. self.__con = self.get_connect()
  60. self.__cur = self.__con.cursor(pymysql.cursors.DictCursor)
  61.  
  62.  
  63. # SELECT
  64. def ins_select(self, query):
  65. try:
  66. self.__cur.execute(query)
  67. return [dict(row.items()) for row in self.__cur.fetchall()]
  68. # return [row for row in self.__cur.fetchall()]
  69.  
  70. except Exception as e:
  71. raise Exception('クエリ実行失敗 [%(message)s] ' % {'message': str(e.message)})
  72.  
  73.  
  74.  
  75. def commit(self):
  76. try:
  77. self.__con.commit()
  78.  
  79. except Exception as e:
  80. raise Exception('コミットエラー [%(message)s] ' % {'message': str(e.message)})
  81.  
  82.  
  83. def close(self):
  84. try:
  85. self.__cur.close()
  86. self.__con.close()
  87.  
  88. except Exception as e:
  89. raise Exception('DBコネクションクローズエラー [%(message)s] ' % {'message': str(e.message)})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement