Is there a way to auto-create a schema on first connection?

7,174 views
Skip to first unread message

Laird Nelson

unread,
Mar 7, 2011, 4:52:43 PM3/7/11
to H2 Database
Hello; thank you for a great product.

Is there a way to create an in-memory database with a schema of my
choosing auto-created for me at the beginning?

For those wondering, no, this is not a Hibernate application, so the
usual advice to just let the JPA provider do it for me automatically
doesn't apply. I really am looking to see if the database itself can
do it.

Thanks much,
Best,
Laird

Thomas Mueller

unread,
Mar 8, 2011, 12:34:34 AM3/8/11
to h2-da...@googlegroups.com, Laird Nelson
Hi,

Yes, H2 supports executing SQL statements when connecting. You could
run a script, or just a statement or two:

String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST";
String url = "jdbc:h2:mem:test;" +
"INIT=CREATE SCHEMA IF NOT EXISTS TEST\\;" +
"SET SCHEMA TEST"
String url = "jdbc:h2:mem;INIT=" +
"RUNSCRIPT FROM '~/create.sql'\\;" +
"RUNSCRIPT FROM '~/populate.sql'";

Please note the double backslash (\\) is only required within Java.

See also http://stackoverflow.com/questions/5225700/can-i-have-h2-autocreate-a-schema-in-an-in-memory-database/5228564#5228564

Regards,
Thomas

Reply all
Reply to author
Forward
0 new messages