Combining Derby embedded mode and server mode

Recently there have been several occasions where I have needed an application to use an embedded driver but also needed to allow for the occasional login to the database externally while the application is executing. Derby works wonderfully for this and starting a server within the application is exceedingly simple. Here I will give just a brief example that should be enough to demonstrate the method. The code fragments here are admittedly simplistic but they work and show the principles cleanly.

 
//First a method to get an embedded connection:

public Connection getConnection() {
    try {
        return DriverManager.getConnection("jdbc:derby:"+dbPath);
    } catch (SQLException e) {
        log.error(e.getMessage(),e);
        return null;
    }
}

//Now a method to start the server for external connections.

private void startDBServer() {
	try {
		server = new NetworkServerControl(InetAddress.getByName("Localhost"),1527);
		server.start(null);
	} catch (Exception e) {
		log.error(e.getMessage(),e);
	}
}

//And lastly let's add a shudown hook to ensure the server gets a chance to exit clean.

private void setShutdownHook() {
	Runtime.getRuntime().addShutdownHook(new Thread() {
		public void run() {
			log.info("**** Application ending ****");
			try {
				server.shutdown();
				} catch (Exception e) {
					log.error(e.getMessage(),e);
				}
			}
    } );
}

That’s the basics and it doesn’t get much easier.

Standard disclaimer - At the time of posting I believe all information contained to be accurate but there is absolutely no warranty or guarantee.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">