Blog logo on a black background with the words "Discover What's Next in Tech!"

Query CSV file with SQL using Java and H2

Sometimes it would be really great if you could query a CSV file in a simple way using SQL.

With the lightweight and free Open source database H2 we only need a few lines of Java code.

In a standard Maven project, we can integrate H2 as follows:

H2 dependency in the pom.xml:

H2 offers the CSVREAD command for reading, which receives the path to the CSV file as a parameter.
This must contain a header line from which CSVREAD automatically generates the column names.
Everything else is standard SQL.

If you want to load the data into a table first, this can be done as follows:

This is ideal if you...

  • would like to index the data beforehand
  • want to run several queries on the data
  • wants to execute a JOIN query with other tables.

Once the table has been created and, if necessary, indexed, the data can be queried as usual using SQL.

For the sake of completeness, here is the code for outputResultSet, which dynamically outputs the ResultSet.


Note: Free sample CSV files for experimenting are available, for example download here.


References:


Matthias Fischer

About ME

Matthias Fischer has a degree in general computer science and has been working as a software developer at doubleSlash since 2006. He has cross-industry experience in IT projects and works with well-known customers such as Deutsche Post Direkt GmbH, BMW AGFederal Printing Office, ZF AG and Zeppelin Systems together. Matthias has extensive expertise in Spring Boot, Java EE and Angular. His main focus is on back-end development, but for some time now he has also been involved in front-end development with Angular. Matthias is also passionate about software quality, automated testing and agile development.

All contributions from Matthias Fischer

Learn more

Further information on our website and in our newsletter

Arrow up