LoginSignup
6
4

More than 5 years have passed since last update.

[Ruby]MySQL上のデータをCSV出力

Posted at
dump.rb
#!/usr/bin/env ruby

require 'mysql2'
require 'csv'

table = "table_name" 
columns = "*" 
host = "localhost" 
username = "user" 
password = "password" 
database = "database" 

client = Mysql2::Client.new(
  host: host,
  username: username,
  password: password,
  database: database,
  stream: true,
  cache_rows: false,
)

results = client.query("select #{columns} from #{table}")

CSV.open("#{table}.csv", "w") do |csv|
  csv << results.fields
  results.each do |row|
    csv << row.values
  end
end
  • stream: true, cache_rows: false あたりが無いとバッファリングしてメモリがあふれる
  • ec2上でやったら時間がUTCになってた
6
4
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
6
4