Boom
Boom

Reputation: 1315

How to import CSV file data into a PostgreSQL table via java code?

I have a csv file which I want to import to table in postgres

The table contains 3 fields (id text, name text, geo geometry). The csv file is in the same format (3 values separate with comma).

I want to use java code in order to import the file (input.csv) into the table (tbl)

How can I do it ? Is there a query which I pass the file path to the DB ?

Upvotes: 2

Views: 6509

Answers (2)

Nilanchala
Nilanchala

Reputation: 5941

You can create a simple Spring boot app to import the CSV data into PostgreSQL. There are two choices

  1. Simple Implementation: Use OpenCSV reader to read the CSV content and JPA/JDBC for storing the data in the DB. This will be fine as long as the CSV files are small.

  2. Using Spring Batch: Spring batch offers robust architecture to efficiently import content from files to DB. It comes in handy with different Reader and Writer implementations to work with different input/output sources.

It is very efficient for processing large data files and offers chunk-based processing, transaction management, etc.

I have written a detailed blog post about this here

Also, there is a video tutorial available on this topic here https://youtu.be/XBW3D1f6CAA

Upvotes: 0

Alexander Makarov
Alexander Makarov

Reputation: 886

You can use OpenCSV to read csv file into java object (here is an example - https://www.geeksforgeeks.org/mapping-csv-to-javabeans-using-opencsv/), and then use Java JPA Repository to insert data into database (here is an example - https://www.baeldung.com/spring-data-crud-repository-save)

Upvotes: 1

Related Questions