suvankar
suvankar

Reputation: 1558

Import CSV file into sqlite3 using Ruby script

I have a ruby script which will read data from some CSV file and import them into sqlite database. I can do this task easily from console using following command:

sqlite> .import <filename> <tablename>
sqlite> .import test.csv PROJECT_REPORT

How can I achieve the same form Ruby script ?

I am doing something similar like following(just a work arround):

 CSV.foreach("timelog.csv") do |row|
     database.execute("INSERT INTO PROJECT_REPORT(
     Date,User,Activity,Comment)
     values
    (#{row[0]}, '#{row[1]}', '#{row[2]}', '#{row[3]}') ")
 end 

Upvotes: 2

Views: 2585

Answers (1)

nathan
nathan

Reputation: 5733

If it's a one time job and you have a simple script that works why not stick with what you already have? If you need to grow the ruby script and want to expand it look at DataMapper (or on of the other ORMs) as an interface to your SQLite database. Create a simple class to contain your Date, User, Activiy and Comment fields and let DataMapper do the heavy lifting to the database.

Updated with datamapper example Here's a simple pseudo-example the datamapper implementation. This is not tested!

#datamapper configuration here
#.
#.
class UserActivity
 include DataMapper::Resource

  property :id,         Serial    
  property :log_date,       DateTime  
  property :user,       Text        
  property :activity    Text
  property :comment     Text
  property :created_at, DateTime
end

So to use it in your example above...

CSV.foreach("timelog.csv") do |row|
  userActivity = UserActivity.new( :log_date => row[0], :user => row[1], :activity => row[2], :comment => row[3])
  userActivity.save!
end

Obviously this isn't a complete solution, but it will get you started.

Upvotes: 2

Related Questions