Claud Posner
Claud Posner

Reputation: 27

H2 Database, merge into table using Java CSVREAD

Good day! I have the following codes to connect to the H2 database and perform queries using Java. However, only the CALL CSVWRITE is working for me.

Here is my code:

public static Result tagImport() {
    String user = session("username");
    Connection connection = null;
    ResultSet resultSet = null;
    Statement statement = null;
    try {
        Class.forName("org.h2.Driver");
        connection = DriverManager.getConnection(
                "jdbc:h2:file:~/data/db", "sa", "");
        statement = connection.createStatement();
        resultSet = statement
                .executeQuery("CALL CSVWRITE('textfiles/tags.csv', 'SELECT * FROM TAG');");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        return ok(dbSuccess.render(user));
}

public static Result tagExport() {
    String user = session("username");
    Connection connection = null;
    ResultSet resultSet = null;
    Statement statement = null;
    try {
        Class.forName("org.h2.Driver");
        connection = DriverManager.getConnection(
                "jdbc:h2:file:~/data/db", "sa", "");
        statement = connection.createStatement();
        resultSet = statement.executeQuery("MERGE INTO TAG (SELECT * FROM CSVREAD('textfiles/tags.csv'));");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        return ok(dbSuccess.render(user));
}

As you can see, the only difference is the query to be executed. I have used the same approach for both but it doesn't seem to work for the tagExport function. I just want to connect to the database again and insert into the table the csv file that I have created with the tagImport function. Kindly help. Thanks!

Upvotes: 1

Views: 1380

Answers (1)

Thomas Mueller
Thomas Mueller

Reputation: 50087

For the MERGE statement, you need to use Statement.executeUpdate() instead of executeQuery()

Upvotes: 1

Related Questions