devxlogo

Create a Database Connection by Passing a DataSource Object

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 directlyfrom 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;    }
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist