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