Using Resource Bundles

From Ingres Community Wiki

Jump to: navigation, search

In most systems it is good to remove configuration specific information from the actual code. Here is an example of using Java property resource bundles to contain driver, URL, and other driver configuration settings outside the actual Java code.

    public static void main (String argv[])
	throws Exception    {
	Connection conn;

	PropertyResourceBundle bp = (PropertyResourceBundle)PropertyResourceBundle.getBundle("db");

	// Every example in the JDBC world has the jdbc.drivers property set at the system level.
	Properties p = System.getProperties();
	p.setProperty("jdbc.drivers", bp.getString("jdbc.drivers"));
	System.setProperties (p);

	/* Instantiate the new driver.  This is the most reliable way to load a jdbc driver because some
	   implementations do not get completely initialized by the getConnection call in the DriverManager.
	   This forces the driver class to completely load and initialize a first new class instance.
	*/
	Object c = Class.forName( bp.getString("jdbc.drivers")).newInstance();

	/* The JDBC driver has a number of connection creation calls.  Here we use the property version.  By
	   using the enumeration of the keys that the owner of the properties file has listed, we can make
	   this code sequence immune to the various different properties used by a particular JDBC driver
	   by copying each resource bundle property into a standard property class property list.
	*/
	Properties dbp = new Properties();
	for (Enumeration e = bp.getKeys(); e.hasMoreElements() ;) {
	    String prop = (String)e.nextElement();
	    dbp.setProperty(prop, bp.getString(prop));
	}
	conn = DriverManager.getConnection(bp.getString("url"), dbp);

A property file might look like the following. The property file needs to be along the CLASSPATH somewhere.

jdbc.drivers:	com.ingres.jdbc.IngresDriver
user:		yourusername
password:	yourpassword
url:		jdbc:ingres://localhost:II7/yourdatabasename

There are many other properties that might be interesting. Because of the property copy loop described in the code fragment, you can add or remove them in the property file without changing your code. See the Ingres Connectivity Guide for complete documentation on JDBC driver properties. Some more interesting ones are "timezone", "autocommit", and "connect_pool".

As with so many code fragment examples, this one does not handle exceptions properly. A working program would need try blocks with these method calls.

Personal tools
Developing With