(I've already seen the H2 database In memory - Init schema via Spring/Hibernate question; it is not applicable here.)
I'd like to know if there's a setting in H2 that will allow me to auto-create a schema upon connecting to it. If it helps, I'm only interested in the in-memory case.
H2 supports various semicolon-separated modifiers at the end of the URL, but I didn't find one for automatically creating a schema. Is there such a feature?
If you are using spring with application.yml the following will work for you
spring: datasource: url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar
Yes, H2 supports executing SQL statements when connecting. You could run a script, or just a statement or two:
Please note the double backslash (
\\
) is only required within Java. The backslash(es) before;
within theINIT
is required."By default, when an application calls
DriverManager.getConnection(url, ...)
and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.
What Thomas has written is correct, in addition to that, if you want to initialize multiple schemas you can use the following. Note there is a
\\;
separating the two create statements.ref : http://www.h2database.com/html/features.html#execute_sql_on_connection