Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load CSV file located in the classpath for H2 Database

For tests purposes, I want to create and fill some tables using SQL scripts as well as CSV files.

So I created a SQL script like this one:

CREATE TABLE T_FOO (
  ...
) as select * from CSVREAD('classpath:/foo.csv');

The foo.csv file exists, and is located in src/test/resources.

When this script is run on Eclipse (where src/test/resources is defined as a source directory and thus is included in the classpath), I get the following error:

Caused by: java.io.FileNotFoundException: resource /foo.csv
    at org.h2.store.fs.FileSystemDisk.openFileInputStream(FileSystemDisk.java:388)
    at org.h2.util.IOUtils.openFileInputStream(IOUtils.java:708)
    at org.h2.tools.Csv.initRead(Csv.java:317)
    at org.h2.tools.Csv.readResultSet(Csv.java:217)
    at org.h2.tools.Csv.read(Csv.java:193)
    ... 49 more

What did I do wrong? How to use correctly the classpath: protocol to load a CSV file?

If I put the complete path for the file (like ... CSVREAD('C:\my-project\src\test\resources\foo.csv');), then it works. But that's not why I want to do :)

Note that I use the latest version of H2 (1.3.153) as I wanted to use the classpath: protocol to load my file.

like image 792
Romain Linsolas Avatar asked Mar 29 '11 15:03

Romain Linsolas


2 Answers

An update to the above answer.

I tried the solution provided above however I was still getting the error, then I tried the below and it works.

Create table tblcountry as select * from CSVREAD('classpath:/country.csv');

The H2 database document needs to be updated.

like image 171
Vineeth Maller Avatar answered Sep 19 '22 17:09

Vineeth Maller


Even if the official docs give the CSVREAD('classpath:/org/acme/data/address.csv') example, Sean Patrick Floyd suggested to remove the leading slash, i.e. having:

CREATE TABLE T_FOO (
  ...
) as select * from CSVREAD('classpath:foo.csv');

and this is working!

like image 22
Romain Linsolas Avatar answered Sep 17 '22 17:09

Romain Linsolas