Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Oct 18, 2004

Create a Database Connection by Passing a DataSource Object

If the DataSource object is not null, a connection is picked up from the connection pool of the datasource. Else, direct connection to the database is created by DriverManager.
 
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
public Connection getConnection(DataSource dataSource)
   {
       String url = "Your_database_url";
       String driver = "Your_database_driver";
       String username = "Your_database_user";
       String pwd = "Your_database_password";
       Connection conn = null;   //Creating a connection object
       if(dataSource == null)  //If datasource does not exist, getting the database connection directly
from database using DriverManager
        {
            try{
                Class.forName(driver);
                conn = DriverManager.getConnection(url, username, pwd);
                conn.setAutoCommit(false);
            }catch(Exception e){e.printStackTrace();}
         }
        else
         { 	//If datasource exists, get the connection from datasource
            try{
                conn = dataSource.getConnection();
                conn.setAutoCommit(false);
                MESACLog.ACLog('d',"Connected");
            }catch(java.sql.SQLException connex){//Connection Pool may be exhausted.
         }
       return conn;
    }
Sujata De
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap