Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Open a JDBC connection (See related posts)

This opens a JDBC connection givine a driver class name, database URL, user name and password. It is possible this method is deprecated and some newer procedure is preferred. I need to look into that.

    /*
    ** driverClass is the JDBC driver class name as a String.
    */

    try
    {
	Class.forName (driverClass);
	connection = DriverManager.getConnection (url,
	    userName, password);
	connection.setAutoCommit (false);
    }
    catch (SQLException ex)
    {
	/*
	** "Connect error"...
	*/
    }
    catch (java.lang.ClassNotFoundException ex)
    {
	/*
	** "Driver error"...
	*/
    }

Comments on this post

JohnMunsch posts on May 24, 2006 at 20:05
May I recommend the code in the snippets "Data Source 101" and "Getting A Data Source From Tomcat" for alternative ways to do this?

Data Source 101 shows the use of the Jakarta Commons DBCP library to create a data source which will implement a pool of database connections for you to open, use, and close easily for those circumstances where you build a Java application that is not inside Spring, Tomcat, or a J2EE server and you don't already have data sources as part of your framework. The other example shows how easy it is to get data sources from Tomcat.

Both of these ways of doing it allow you to decouple your JDBC code from the details of knowing the kind of database to which you are connecting or any other details of the connection and you get free pooling services (a performance boost). Since data sources are common across many frameworks and even among applications which do not use a framework at all your code will be more portable as well.
mikewilsonuk posts on Jun 22, 2006 at 14:54
Thanks for the tip -- I suspected there was a better way.

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts