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:



