Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- " Pythonからmysqlへの接続ラッパー
- """
- import sys
- import os
- import pymysql.cursors
- ABS_DIR_PATH = os.path.abspath(os.path.dirname(__file__))
- sys.path.append(ABS_DIR_PATH + '/../') # for const
- # sys.path.append(ABS_DIR_PATH + '/lib')
- import constant as const
- class DB:
- def __init__(self):
- pass
- @staticmethod
- def get_connect():
- try:
- conn = pymysql.connect(
- host=const.RDS_HOST,
- port=const.DB_PORT,
- db=const.DB_NAME,
- user=const.DB_USERNAME,
- password=const.DB_PASSWORD)
- cur = conn.cursor()
- # cur.execute("SET search_path = " + const.DB_SET_SEARCH_PATH)
- print "connection!!"
- return conn
- except Exception as e:
- print "DBコネクションエラー"
- # INSERT
- # UPDATE
- @classmethod
- def execute(cls, query):
- try:
- with cls.get_connect() as con:
- with con.cursor() as cur:
- cur.execute(query)
- con.commit()
- # 重複する場合を例外処理
- except psycopg2.IntegrityError as e:
- pass
- except Exception as e:
- raise Exception('クエリ実行失敗 [%(message)s] ' % {'message': str(e.message)})
- def conn(self):
- self.__con = self.get_connect()
- self.__cur = self.__con.cursor(pymysql.cursors.DictCursor)
- # SELECT
- def ins_select(self, query):
- try:
- self.__cur.execute(query)
- return [dict(row.items()) for row in self.__cur.fetchall()]
- # return [row for row in self.__cur.fetchall()]
- except Exception as e:
- raise Exception('クエリ実行失敗 [%(message)s] ' % {'message': str(e.message)})
- def commit(self):
- try:
- self.__con.commit()
- except Exception as e:
- raise Exception('コミットエラー [%(message)s] ' % {'message': str(e.message)})
- def close(self):
- try:
- self.__cur.close()
- self.__con.close()
- except Exception as e:
- raise Exception('DBコネクションクローズエラー [%(message)s] ' % {'message': str(e.message)})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement