PostgreSQLと同様、いわゆる本格的なデータベースの一つであるMySQLの例です。Pythonに対応したMySQLドライバも数種類あるようですが、本サイトではPyMySQLを使用します。
ドライバのインストール
下記コマンドを入力しPyMySQLをインストールしてください。
※これはpipがインストールされていることを前提としています。インストールしていない場合はpipの使い方とインストールを参照してください。
pip install PyMySQL
insertサンプル
データ登録は次のように行います。
import pymysql
connector = pymysql.connect(
host='localhost',
db='sdb',
user='msusr',
passwd='mspsw',
charset='utf8',
)
cursor = connector.cursor()
sql = "insert into test_table values('1','python')"
cursor.execute(sql)
sql = "insert into test_table values('2','パイソン')"
cursor.execute(sql)
sql = "insert into test_table values('3','ぱいそん')"
cursor.execute(sql)
connector.commit()
cursor.close()
connector.close()
まずは1行目でpymysqlモジュールのインポートを行います。続く3行目から9行目の記述でデータベースへ接続、引数には(ホスト名, データベース名, ユーザー名, ユーザーのパスワード, 文字コード)を設定します。10行目でカーソルを取得し、12行目から17行目で指定のSQL文を実行します。19行目でコミットを行い、最後はデータベース接続を閉じて終了です。
selectサンプル
データ参照は次のように行います。先程登録したデータを見てみましょう。
import pymysql
connector = pymysql.connect(
host='localhost',
db='sdb',
user='msusr',
passwd='mspsw',
charset='utf8',
)
cursor = connector.cursor()
cursor.execute('select * from test_table order by code')
result = cursor.fetchall()
for row in result:
print('===== Hit! =====')
print('code -- ' + row[0])
print('name -- ' + row[1])
cursor.close()
connector.close()
===== Hit! ===== code -- 1 name -- python ===== Hit! ===== code -- 2 name -- パイソン ===== Hit! ===== code -- 3 name -- ぱいそん
pymysqlモジュールのインポート後、データベースへ接続します。10行目でカーソルの取得を行い、select文を実行。fetchallを使用すると結果がタプルで返ってきます。
