How to import CSV file to the Database
Today I learned how to import CSV data file to the database, and populate the table.
Imagine you have this migration in your application with the following columns:
create table(:users) do
add(:first_name, :string, null: false)
add(:last_name, :string, null: false)
add(:username, :string, null: false)
add(:email, :string, null: false)
end
And this would be the CSV file:
First Name,Last Name,Username,Email
John,Doe,john_doe,john@doe.com
Jane,Doe,jane_doe,jane@doe.com
And how can I import my CSV file to the users’ table on the database?
~$ psql -U user -d database <<USERS
COPY users(first_name, last_name, username, email) FROM '/path/to/users.csv' DELIMITER ',' CSV HEADER;
USERS
After finishing, you will receive and output with COPY 2
the quantity of copies into your table.