How To Get JDBC Connection

Connect with

1. Get JDBC Connection with MySQL
** Pre-requisite:**

include mysql connector dependency jar in application lib

Include mySQL connector java dependency in pom.xml file , if using maven as build tool in your application:

 
 
 mysql
 mysql-connector-java
 5.1.37


        
/**
 * This method is used to get JDBC connection from MySQL.
 * 
 * @return 
 */
public static Connection getDBConnectionMySql() {
	Connection aConnection = null;

	try {
		Class.forName("com.mysql.jdbc.Driver");
		aConnection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/spring_mvc", "root", "root");

	} catch (Exception exc) {
		exc.printStackTrace();
		// logger.error("getDBConnection():Error in database "+exc.getMessage());
	} finally {
		// release resource if done with
	}
	return aConnection;
}

2. get Connection from MS-SQL database
– add jar file in you project lib or classpath
– or add dependency in you pom.xml maven metadata configuration file.

 /**
  * This method is used to get JDBC connection from MS-SQL server.
  * 
  * @return
 */
public static Connection getDBConnectionMSSQLServer() {
	Connection aConnection = null;
  try {
	Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
	aConnection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=dbname",   "userid", "pwd");
  } catch (Exception exc) {		
     	logger.error("getDBConnection():Error in database "+exc.getMessage());  
 }         
 return aConnection;
} 

Once you done with connection release the occupied resources, you know this very valuable resource, if you not release and not using connection pooling , you may not at particular point of time.

Release Connection

/**
 * This method release the database connection  
 * @param aConnection
 * @throws SQLException
 */
public static void releaseConnection(Connection aConnection) {
  if (aConnection != null) {
	try {
	   aConnection.close();
	} catch (SQLException e) {
	//logger.error("releaseConnection():Error in closing connection"+e.getMessage());
		//System.out.println(" exception : " + e.getMessage());
	}
  }
}

Release Statement

/**
 * This method release the database Statement  
 * @param aConnection
 * @throws SQLException
 */
public static void releaseStatement(Statement aStatement) {
  if (aStatement != null)
	try {
	aStatement.close();
	} catch (SQLException e) {
		//logger.error("releaseStatement():Error in closing statement"+e.getMessage());
  }
}

Release ResultSet

/**
 * This method release the ResultSet  
 * @param aConnection
 * @throws SQLException
 */
public static void releaseResultSet(ResultSet aResultSet) {
  if (aResultSet != null)
	try {
	  aResultSet.close();
	} catch (SQLException e) {
		//logger.error("releaseResultSet(): Error in closing resultset"+e.getMessage());
	}
}

Connect with

1 thought on “How To Get JDBC Connection

Leave a Reply

Your email address will not be published. Required fields are marked *