Created
April 14, 2014 05:30
-
-
Save gin0606/10618604 to your computer and use it in GitHub Desktop.
Excelで作られたCSVをsqliteに適当に突っ込む奴
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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