Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a check I used to (re)create the H2 database:</p> <pre><code>// IMPORTANT A sorted list of table names. private static final String[] REQUIRED_TABLES = { "USER", ... }; public static final String CREATE_USER = "create table USER (...)"; private boolean schemaExists() throws SQLException { final List&lt;String&gt; requiredTables = Arrays.asList(REQUIRED_TABLES); final List&lt;String&gt; tableNames = new ArrayList&lt;String&gt;(); final Connection conn = dataSource.getConnection(); try { final Statement st = conn.createStatement(); final ResultSet rs = st.executeQuery("show tables"); while (rs.next()) { tableNames.add(rs.getString("TABLE_NAME")); } rs.close(); st.close(); } finally { if (conn != null) { conn.close(); } } Collections.sort(tableNames); return tableNames.equals(requiredTables); } private void initializeDatabase() throws SQLException { final Connection conn = dataSource.getConnection(); try { if (schemaExists()) { return; } final Statement st = conn.createStatement(); st.executeUpdate(CREATE_USER); conn.commit(); } finally { if (conn != null) { conn.close(); } } } </code></pre> <p>And you just call:</p> <pre><code> initializeDatabase(); </code></pre> <p>Notice the list of required tables has to be sorted because I use <code>List.equals()</code> to compare two lists. It would probably be better to also programmatically sort the required tables list too.</p> <p>It's not fool-proof (not checking if any table exists and if it should be altered) but it works for me.</p> <p>Take a look at the <a href="http://www.h2database.com/html/grammar.html#show" rel="nofollow">SHOW</a> command for other uses.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload