3

I have an application with h2 database. I want to create .sql file using SCRIPT command in Java.

If I am executing it using Prepared Statement:

PreparedStatement stmt = con.prepareStatement("SCRIPT");
ResultSet rs = stmt.executeQuery();

Then how can I able to get whole result in single String. I am new to Java so unable to find the way out to get result of that query because it doesn't contains column names in it.

Then I will write it in file using InputStream.

0

1 Answer 1

4

If you want to backup into a file, the content of your H2 instance as a SQL script, you can directly use SCRIPT TO 'path/to/my/file.sql'.

try (Connection con = ...;
     Statement stmt = conn.createStatement()) {
    stmt.executeQuery(String.format("SCRIPT TO '%s'", sqlFilePath));
}

If you want to backup it as a ZIP archive, you can use BACKUP TO 'path/to/my/file.zip'.

try (Connection con = ...;
     Statement stmt = conn.createStatement()) {
    stmt.executeQuery(String.format("BACKUP TO '%s'", zipFilePath));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ok now i got idea on how to move it to file. Will try it and update.
It works fine but stmt.executeUpdate needs to be replaced with stmt.executeQuery
Maybe I am doing somethig wrong, but after creation execute this statemtent and only get one file with "CREATE USER IF NOT EXISTS "SA" SALT '4d7ed4bf3238b907' HASH '8326f36da8ddeddb5edb065ad2b6ac59536448f26d99ebf8c3c70e8c018a877d' ADMIN;" But I know that exist tables and other objects in database.....any help?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.