Hi Thomas,
Here is a non-simple way of doing it.
String initUrl = dbUrl
// Setup db listener. Note that H2 instatiates helper class itself.
+ ";DATABASE_EVENT_LISTENER='"
+ H2Helper.class.getName() + "'"
// Let Ninan handle db close on shutdown
+ ";DB_CLOSE_ON_EXIT=FALSE"
// Don't close db when last connection is closed
+ ";DB_CLOSE_DELAY=-1";
// Specify other props here...
logger.debug("Creating H2 datasource");
JdbcDataSource ds = new JdbcDataSource();
ds.setURL(initUrl);
ds.setUser(dbUser);
ds.setPassword(dbPassword);
logger.debug("Creating H2 pool");
pool = JdbcConnectionPool.create(ds);
logger.debug("Creating H2 config connection");
JdbcConnection conn = (JdbcConnection) ds.getConnection();
int waited = 0;
while (!h2Opened) {
try {
++waited;
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
logger.debug("Waited " + waited + " ms for H2 to open");
logger.debug("Loading H2 pagestore");
SessionInterface sessionInterface = conn.getSession();
DataHandler dataHandler = sessionInterface.getDataHandler();
Database database = (Database) dataHandler;
PageStore pageStore = database.getPageStore();
boolean isNew = pageStore.isNew();
logger.debug("H2 pagestore is new: " + isNew);
if (isNew) {
logger.info("Creating H2 database at " + dbUrl);
Statement stat = conn.createStatement();
stat.execute("RUNSCRIPT FROM 'db/ninandb.sql'");
JdbcUtils.closeSilently(stat);
}
JdbcUtils.closeSilently(conn);
logger.debug("Resetting H2 datasource url to " + dbUrl);
ds.setURL(dbUrl);
The H2Helper class implements DatabaseEventListener and sets the
h2Opened flag in the above code.
All code available at
http://ninan.svn.sourceforge.net/viewvc/ninan/trunk/ninan-backend/src/main/java/dk/team/ninan/backend/db/
Cheers
/Max
On 18-12-2011 18:54, Thomas Mueller wrote:
Hi,
Is there a way to execute a sql script at database creation ?
Currently not. What you could do is use CREATE ... IF EXISTS. I know
this is quite limited, but currently there is no other (simple) way
I'm afraid.
Regards,
Thomas
--
You received this message because you are subscribed to the Google Groups "H2
Database" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/h2-database?hl=en.