DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Open A JDBC Connection

05.14.2006
| 17825 views |
  • submit to reddit
        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

Snippets Manager replied on Wed, 2006/04/26 - 3:32pm

Thanks for the tip -- I suspected there was a better way.

Snippets Manager replied on Mon, 2006/02/27 - 11:12pm

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.