Backo
Backo

Reputation: 18881

How to import data to the database from a CSV file?

I am using Ruby 1.9.2, the Ruby on Rails v3.2.2 gem and the MySQL database. I would like to import data to the database from a CSV file containing world cities. I think this process should be made by running a RoR migration but I don't know how to properly proceed.

In particular, I don't know where (that is, in which directory relating my RoR application) I should put the CSV file and how to access that file from my migration file in order to add data to the database.

Upvotes: 0

Views: 2754

Answers (2)

awenkhh
awenkhh

Reputation: 6131

I do a lot of importing from csv files to the database. I place the csv files in the db folder. Then I create rake tasks so that I can simply call

$ rake db:import:whatever

For parsing the csv files I use the csv library - you have to set require 'csv'. The importer are models in app/models. Here are some code snippets which show, how to do the import:

https://gist.github.com/4013876

I hope this helps for a start ...

Upvotes: 3

akhilless
akhilless

Reputation: 3219

MYSQL can import CSV files directly. To do it you should log-in to your server via SSH (or get to the command line somehow) and call the following commands:

$ mysql -u yourUserName -p
Enter password:
$ mysql> load data local infile 'c:\path_to_file\filename.csv' into table yourTableName character set utf8 fields terminated by ',' enclosed by '"' lines terminated by '\r\n' (field1, field2, field3);

Upvotes: 0

Related Questions