大量のINSER文を発行する必要があったので、スクリプトで書いてみた。
RubyとMySQLはインストールしてある前提
ディレクトリとファイルの作成
terminal
$ mkdir ruby_scripts && cd $_
$ touch test.rb
$ chmod 755 test.rb
test.rbの中身
test.rb
#!/usr/bin/ruby
require 'mysql2'
connection = Mysql2::Client.new(host: "localhost", username: "root", password: 'pass', :encoding => 'utf8', database: 'database_name')
# 自分の環境に合わせる
selectSql = "SELECT id FROM table WHERE flag = 1;"
# こんな単純なSELECT文ならそもそもスクリプトを書く必要はないと思うが...
res = connection.query(selectSql)
res.each do |r|
code = r["id"]
# 実行結果のINSERT文内の変数rにハッシュがそのまま入ってしまうので、値だけを取り出して新しい変数codeに代入
puts "INSERT INTO table2 (id, code) VALUES (2, '#{code}');"
end
Gemfileの作成
$ bundle init
Gemfileの一番下に記述
gem "mysql2"
bundle install
$ bundle install
実行
bundle exec ruby test.rb > hoge.sql
上記のコマンドを実行して作られるhoge.sqlをsourceコマンドで実行すればデータをINSERTできます。