MySQLdb

MySQLdb User’s Guide

MySQLdb User’s Guide

インストール

py -m pip install MySQL-Python

上記モジュールのインストールで、。”‘config-win.h’:No such file or directory”というエラーが出て失敗するときは、代わりに基本的なMySQLの機能だけを有効にする以下のモジュールをインストールするとよい。

py -m pip install PyMySQL

インポート

import MySQLdb

オペレーションフロー

MySQLのオペレーションは7つのステップからなる。

  1. Create connection
  2. Create cursor
  3. Create Query string
  4. Execute the query
  5. Commit to the query
  6. Close the cursor
  7. Close the connection

データベース接続

connect = MySQLdb.connect(
    host = 'localhost',    # Pythonを実行するPCのアドレス(localhost)
    port = 10022,    # 上記で指定したlocalhostの適当なPort
    user = RDS_MySQL_userID,
    db = RDS_database_name,
    passwd = RDS_database_password,
    local_infile = 1    # "LOADDATA IN FILE" for CSV Import
)
cursor = connect.cursor()
  • データーベースのエンドポイントは、すでにSSHTunnelForwarderでパラメーターとして指定しているので、dbにはデーターベース名だけを指定する。

クエリの実行

cursor.execute(sql)

クエリ実行結果取得

cursor.fetchall()

データベースを閉じる

cursor.close()
  • Connectを閉じると自動的にデータベースが閉じるという説もある。

MySQLの接続を閉じる

connect.close()
  • Cursorを閉じた後に実行する。