Skip to content

Instantly share code, notes, and snippets.

@gin0606
Created April 14, 2014 05:30
Show Gist options
  • Save gin0606/10618604 to your computer and use it in GitHub Desktop.
Save gin0606/10618604 to your computer and use it in GitHub Desktop.
Excelで作られたCSVをsqliteに適当に突っ込む奴
require 'fileutils'
require 'csv'
require 'sqlite3'
DB_FILE_NAME = 'tmp.sqlite';
FileUtils.rm(DB_FILE_NAME) if File.exist?(DB_FILE_NAME)
DB = SQLite3::Database.new(DB_FILE_NAME)
def create_table(file_name)
csv = CSV.open(file_name, 'r', encoding: "SJIS")
csv_header = csv.readline
tabel_name = File::basename(file_name, '.csv')
DB.execute "create table #{tabel_name}(#{csv_header.join(', ')});"
csv.readlines.each do |row|
DB.execute "insert into #{tabel_name} values(#{array_to_sql_value(row)})"
end
end
def array_to_sql_value(row)
"#{row.collect{|v| "'#{v.encode('UTF-8')}'"}.join(', ')}"
end
csv_files = Dir.glob("#{Dir.pwd}/*.csv")
csv_files.each {|file_name|
create_table(file_name)
}
DB.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment