Python 3でMySQLデータベースを操作する方法

PyMySQLの導入と使用法

MySQLデータベースをPython 3で操作するには、PyMySQLというサードパーティライブラリが必要です。インストール方法は以下の通りです:

$ pip install pymysql

データベース操作の基本手順は以下の通りです:

  1. 接続確立: connection = pymysql.connect()
  2. カーソル生成: cursor = connection.cursor() または辞書型結果用の cursor = connection.cursor(pymysql.cursors.DictCursor)
  3. SQL実行: cursor.execute(sql)
  4. 結果取得(読み取り)/変更確定(書き込み): cursor.fetchall() / connection.commit()
  5. カーソルと接続の終了: cursor.close(); connection.close()

カーソル(cursor) は、データベースの実行結果を一時的に保持するバッファへのポインタです。PyMySQLではこのカーソルを通じてSQLを実行し、結果を取得します。

基本的な使用例

import pymysql

# 1. 接続確立
connection = pymysql.connect(host='localhost',
                           port=3306,
                           user='admin',
                           password='password123',
                           db='sample_db',
                           charset='utf8mb4')

# 2. カーソル生成
cursor = connection.cursor()

# 3. データ取得(SELECT)
cursor.execute("SELECT * FROM employees WHERE department = 'Sales'")

# 4. 結果取得
results = cursor.fetchall()
print(results)

# 3. データ変更(INSERT)
cursor.execute("UPDATE employees SET salary = 50000 WHERE id = 1001")

# 4. 変更確定
connection.commit()

# 5. カーソルと接続の終了
cursor.close()
connection.close()

クエリ操作の詳細

cursor.execute() を使用してクエリを実行した場合、戻り値は影響を受けた行数であり、実際の結果セットは cursor.fetchone()/fetchmany()/fetchall() で取得する必要があります。

  • cursor.fetchone():1行取得(取得後は結果セットから削除される)
  • cursor.fetchmany(3):最大3行取得(タプルのリスト形式で返す)
  • cursor.fetchall():全行取得(タプルのリスト形式で返す)

注意点:

cursor.execute("SELECT * FROM employees WHERE department = 'Sales'")
print(cursor.fetchone())  # ('山田太郎', 'Sales', 45000)
print(cursor.fetchone())  # None(先の取得で結果が空になった)
print(cursor.fetchall())  # ()(同様に空)

# 再利用が必要な場合は変数に代入
cursor.execute("SELECT * FROM employees WHERE department = 'Sales'")
results = cursor.fetchall()
print(results)  # ('山田太郎', 'Sales', 45000)
print(results)  # ('山田太郎', 'Sales', 45000)

辞書形式の結果を取得するには、DictCursorを使用します:

cursor = connection.cursor(pymysql.cursors.DictCursor)
result = cursor.fetchone()  # {'name': '山田太郎', 'department': 'Sales', 'salary': 45000}

データ変更操作

変更操作は即座に反映されず、connection.commit()で確定する必要があります。トランザクションとロールバックもサポートされています。

try:
    cursor.execute("INSERT INTO employees (name, department) VALUES ('佐藤花', 'Marketing')")
    cursor.execute("INSERT INTO employees (name, department) VALUES ('鈴木健')")  # カラム不一致エラー
    connection.commit()
except Exception as e:
    connection.rollback()  # 全ての変更をロールバック
    print(f"エラー発生: {str(e)}")

データベース操作のクラス化

import pymysql

class MySQLHandler:
    def __init__(self):
        self.connection = pymysql.connect(
            host='localhost',
            port=3306,
            user='admin',
            password='password123',
            db='sample_db',
            charset='utf8mb4',
            autocommit=True
        )
        self.cursor = self.connection.cursor(pymysql.cursors.DictCursor)
    
    def execute_query(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()
    
    def execute_update(self, sql):
        try:
            self.cursor.execute(sql)
        except Exception as e:
            self.connection.rollback()
            print(f"更新失敗: {str(e)}")
    
    def close_connection(self):
        self.cursor.close()
        self.connection.close()

# 使用例
handler = MySQLHandler()
print(handler.execute_query("SELECT * FROM employees WHERE department = 'Sales'"))
handler.execute_update("UPDATE employees SET salary = 55000 WHERE id = 1002")
handler.close_connection()

タグ: PyMySQL mysql-connector python-3 database-operations sql-queries

7月28日 07:09 投稿