Posts Tagged Java

Combining Derby embedded mode and server mode

Posted by Roger Cuddy on Wednesday, 29 April, 2009
No Gravatar

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.

Author Roger Cuddy claims no special knowledge of subject beyond a strong interest and slight opinion. Your mileage may vary.
  • Share/Bookmark

Improve the web with Nofollow Reciprocity.