Python (MySQL)

mysqlclient をインストールしていること

pip install mysqlclient

MySQLdb をインポート。下記のクラスで基本の読み書きはできるかと。

import MySQLdb

class MySQL() :
    def __init__(self, **config) :
        """
        コンストラクタ
        
        Parameters
        ----------
        'host' : str
            ホスト名
        'user' : str
            ユーザー名
        'passwd' : str
            パスワード
        'db' : str
            接続先データベース
        """
        # 接続
        self.conn = MySQLdb.connect(**config)
        # 自動コミット無効
        self.conn.autocommit(False)
        # カーソル生成
        self.cursor = self.conn.cursor()

    def __del__(self):
        """
        デストラクタ
        データベースへの接続を切断する
        """
        # with ステートメントを使用していなければ切断処理
        if self.conn is not None:
            self.cursor.close()
            self.conn.close()

    def __enter__(self) :
        """
        for with statement
        """
        return self

    def __exit__(self, ex_type, ex_value, trace):
        """
        for with statement
        """
        self.cursor.close()
        self.conn.close()
        self.conn = None

    def query(self, sql : str) :
        """
        SQL実行

        Parameters
        ----------
        sql : str

        Returns
        ----------
        クエリ結果

        """
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()

        except Exception as e:
            raise e

    def execute(self, sqls : list) :
        """
        SQL実行

        Parameters
        ----------
        sqls : list
            SQL
        """
        try:
            for sql in sqls :
                self.cursor.execute(sql)

        except Exception as e :
            self.conn.rollback()
            raise e

        finally :
            self.conn.commit()
タイトルとURLをコピーしました