Logo

dev-resources.site

for different kinds of informations.

How to import CSV file to the Database

Published at
12/19/2023
Categories
elixir
ecto
postgres
tutorial
Author
Herminio Torres
Categories
4 categories in total
elixir
open
ecto
open
postgres
open
tutorial
open
How to import CSV file to the Database

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,[email protected]
Jane,Doe,jane_doe,[email protected]
...

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 an output with COPY 2 the number of copies in your table.

Featured ones: