Created
November 5, 2008 12:51
-
-
Save arockwell/22324 to your computer and use it in GitHub Desktop.
This file contains 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
module FileReader | |
def self.output(filename, delimeter, table_name, column_names) | |
result = Array.new | |
File.open(filename).each do |line| | |
# split the line on commas and remove trailing white space | |
columns = line.split(delimeter).each {|x| x.strip!} | |
# escape ' characters | |
columns.map! { |x| x.gsub(/'/, "''") } | |
# construct the insert statement | |
begin_sql = "insert into #{table_name} " + column_names.join(", ") | |
sql = begin_sql + " values (" + columns.join(", ") + ")" | |
# add the statement to the array | |
result << sql | |
end | |
return result | |
end | |
# open filename and write every element of data to the file | |
def self.write_file(filename, data) | |
f = File.new(filename, "w") | |
data.each { |line| f.puts(line) } | |
end | |
end | |
column_names = [ "col1", "col2", "col3" ] | |
table_name = "test_table" | |
filename = "C:\data.txt" | |
out_file = "C:\proc_data.txt" | |
result = FileReader.output(filename, ",", table_name, column_names) | |
puts result | |
FileReader.write_file(out_file, result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment