1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Windowsバッチ MySQLのコマンドでSQLファイルに引数を渡す動作を実現する

Last updated at Posted at 2022-07-31

概要

OracleのSQL*Plusなら以下のように外部sqlファイルを定義してコマンドで引数を渡せますが、MySQLのコマンドのmysqlでは引数を渡すことができません。引数は渡せませんが、同じような処理を実現することはできることが分かったのでまとめます。背景としては作っているツールにて、バッチファイルでデータを取得する必要がありました。MySQLバージョンは8.0.29、Windows10です。

oracle.sql
SELECT * FROM test WHERE id = &1
oracle.bat
sqlplus user/password@ConnectionString @c:\oracle.sql 1
MySQL.sql
SELECT * FROM test WHERE id = @param_id
MySQL.bat←できない
mysql -u user -D test -ppassword < MySQL.sql 1

解決

流れとしては、MySQLにセッション固有のユーザ定義変数(この例だと、@param_id = 1)を設定して、そのあと、ユーザ定義変数を使ったSQLを実行します。バッチファイルで実行する場合、この流れの2つの処理をmysqlコマンドの1行で実行する必要がありましたので、-eオプションを使って実現させました。実行結果はtest.tsvに出力されるようにしています。(sqlファイルのパスや、出力先パスは正しく指定する必要があります。)

MySQL.sql
SELECT * FROM test WHERE id = @param_id
MySQL.bat
mysql -u user -D test -ppassword -e "set @param_id = 1; source MySQL.sql;" > test.tsv

バッチファイルで処理をする場合、こんな感じになりそうです。文字列結合を使って-eの後ろの文字列を作る感じになります。

MySQL.bat
set paramid=1
set s1=set @param_id =
set s2=; source test.sql;
set execSTR="%s1%%paramid%%s2%"
mysql -u user -D test -ppassword -e %execSTR% > test.tsv
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?