0
0

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 3 years have passed since last update.

RubyでMySQLに接続し、大量のINSERT文を作成する

Last updated at Posted at 2021-03-05

大量の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できます。

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?