3
5

More than 3 years have passed since last update.

MySQL で Python を書く

Last updated at Posted at 2019-11-14

Mysql Workbench Scripting Shell

みんな知っているMySQL Workbench
mysqlworkbench.png

MySQL Workbench の Scripting -> Scripting Shell という項目からSQLの実行をPythonで制御できるエディタが開ける

mysqlworkbench2.png

エディタを新規に起動するとすでにテンプレートでPython スクリプトが記述されているが、このimport grtという一行が重要で、これによって Mysql Workbench のエディタがPythonで制御できるようになっている。

例えばgrt.root.wb.sqlEditors[0].executeScript()関数を使えばPython script 内の文字列をSQLとして実行できる
文字列にはstring formatが適用できるので変数を柔軟にSQLに組み込むことができる

スクリプト例

例えばある表Aの上位100件に対して、表Aのcountyカラムに応じたレコードを表Bに挿入する処理などは次のように書ける

import grt
#import mforms
query_select = "select * from table_A limit {};"
query_insert = "insert into table_B (country) {};"
result = grt.root.wb.sqlEditors[0].executeScript(query_select.format(100))

n = result[0].rowCount -1
for i in range(0, n):
    country = result[0].stringFieldValueByName("country")
    editor.executeScript(query_insert.format(country+"_duplicated"))
    result[0].nextRow()

SQLマスターにならないと書けないような処理でもPythonで書けば簡単に書けることが結構あります
一番のボトルネックは自分がコードを書く時間という格言もありますので、積極的にMySQLでPythonを使っていきましょう

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5