Standalone java apps vs JNDI datasources

This is another post as a memory jogger for me.

Whenever I switch back to java I have trouble remembering the evolving history of setting up mysql connections. Back in the dark ages, you used to do this with Class.forName. But by the time I started writing servlets initially, it was being done instead with DriverManager. Then along came DataSources which could be set up in JNDI. A much more elegant solurtion, as long as you have a container to offer the JNDI service. Most of the active java I have is servlets running in Tomcat, and these are happily set up to use DataSource objects, and the DataSources are all described in the context and picked off from there.

But what about the occasions when I have some standalone java application. Today I downloaded all the FAA NASR database, and wanted to reload my local copy of the Airport, Nav and Fix data for the Tomcat applets to look up in. The code that parses the FAA text files and uploads to the MySQL database is a standalone java application, with a main method. Does anybody still do that? There is no JNDI, and there is no Context. I had already solved this problem once but since I hadn’t posted anything to help me remember, I had to figure it all out again. I don’t find any easy way to get DataSource objects set up in a standalone java app. One set of posts I read described how to create a local JNDI environment. That seems like overkill to support a very small java app.

I don’t have an elegant solution. All I’ve done is overload the constructors for the class that wraps the database, and have both mechanisms. The standalone java apps only run on my local box, doing stuff like populating databases. So they invoke a constructor passing a string that gets passed to a DriverManager.getConnection call. It saves the string and sets an instance boolean so other methods of the wrapper class know to get connections through DriverManager. The constructor invoked from within the servlets uses the Context to look up the DataSource objects in JNDI, and stores the DataSource in an instance variable.