LoginSignup
3
2

More than 5 years have passed since last update.

RubyでmysqlのデータをCSV出力する

Last updated at Posted at 2017-04-08

mysqlに保存されているデータをCSVで出力する方法。
スクレイピングし終わったデータをCSVで出したいときなどに使ってます。

require 'csv'

res = client.query('select * from t_name')

csv_string = CSV.generate(:force_quotes => true) do |csv|
  csv << ['col1', 'col2'] #CSVの一行目のカラム名を書きます

  res.each do |row|

    csv << [
      row['col1'],
      row['col2']
    ]
  end
end

File.open('file_name.csv', "w", encoding: "SJIS", undef: :replace) do |file|
  file.write(csv_string)
end

3
2
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
2