简体   繁体   中英

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.

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 ...

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM