Wednesday, June 3, 2015

Connect the Database through JDBC in Java

Java Database Connectivity (JDBC) is a Java based API that is primarily used in programming of Java applications for interfacing with various SQL supporting databases and other data sources such as spreadsheets or flat files.
Java Database Connectivity (JDBC) is one of the Application Program Interface (API) specifications that allow a user to utilize SQL for connecting Java programs to a database.
JDBC is a call-level interface that allows programmers to write Java applications that execute SQL commands on an external database. Using standard library routines, the Java program connects to the database, then uses JDBC to send queries and update code to the database. The program retrieves and processes the results received from the database in answer to the queries, and then closes the connection to the database.
Since Java runs on most platforms, JDBC makes it possible to write a single Java application that will run on multiple platforms and interact with different databases.
JDBC was developed by JavaSoft, a subsidiary of Sun Microsystems.

Steps to use JDBC in a Java Program

1) The JDBC facilitates the connection to a database through a "Connection object" which is initiated through a "DriverManager object".
2) The Connection object is used to create a "Statement object" for SQL query.
3) The Statement object is used to execute the SQL query to return the results through "ResultSet object".
4) Using the ResultSet object, the results of the query can be displayed by looping through the retrieved record sets.

JDBC Components

JDBC is comprised of the following components:
  • JDBC API — provides programmatic access to relational data from the Java programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment.
-Note- The JDBC API is included in both Java EE (Enterprise Edition) and Java SE (Standard Edition). The JDBC API (current version 4.0) is part of the two Java packages,namely, java.sql and javax.sql which are available both in Java EE as well as Java SE.
The JDBC API can be used for both two-tier as well as three-tier processing models for database access.
The two-tier model is typical client-server architecture in which the user’s machine is the client and the data source resides on the server. By the application of a JDBC driver in a Java application, the user on the client can communicate directly with the data source on the server.
The three-tier model involves middleware, where the data source processes the commands and via middleware, the data is sent to the client. The middle tier, which acts as middleware, can be developed using the Java platform. Using this middle tier, the JDBC API can facilitate access to a data source. A middle tier application, developed using Java programming language, can add inbuilt features of multithreading and security in the Java application. The three-tier model normally offers better control over data updates and data security.
  • JDBC DriverManager class — defines objects which can connect Java applications to a JDBC driver.
  • JDBC Test Suite — used to determine that JDBC drivers will run your program.
  • JDBC-ODBC Bridge — provides JDBC access via ODBC drivers. The ODBC binary code must be loaded onto each client machine that uses this driver.
Since ODBC ( Open Database Connectivity ) is a very popular API for database connectivity and the OBDC drivers are available for most of the data sources and database management systems, the JDBC-ODBC bridge is particularly useful on a network where client installation is not an issue, and also, for implementing a three-tier architecture while coding an application server in Java.

//PACKAGE STATEMENTS
package com.marks.db;
/**
* @author Achappan M
* created on 26/04/2008 
*/
//IMPORT STATEMENTS
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
/**
* This Class is used to create the jdbc connection 
* and use the query for select, update, delete
*/
public class DBConnection {
//intialise the Logger for this Class
static Logger mLogger = Logger.getLogger(DBConnection.class.getPackage().getName());
//this method is used to get Create connection from postgre sql driver
public static Connection getConnection() {
Connection connection = null;
try{
//load the pgsql driver
Class.forName("org.postgresql.Driver");
System.out.println("Hi Achappan!! your pgsql driver Loaded Successfully");
// create the datasource
String url = "jdbc:postgresql://10.2.0.5:5432/acti"; System.out.println("Print URL " + url);
// register the driver in Driver Manager and establish the connection from them
connection = DriverManager.getConnection(url, "postgres", "postgres");
System.out.println("Connection Established");
}
catch(Exception exception)
{
System.out.println(exception.getMessage()); }
return connection;
}
//it is used to close the connection
public static void closeConnection(Connection pConnection)
          {
try{
                  if (pConnection != null){
                  pConnection.close();
                  pConnection = null;
}
}
               catch (Exception e){
               System.out.println("Error occured while closing the exception  " + e.getMessage());
} }
/**
* This function is used to Close the statement.
* @param pStatement
*/
public static void closeStatement(Statement pStatement) throws BusinessException
          {
        try{
                  if (pStatement != null)
                  {
pStatement.close(); pStatement = null; } }
              catch (SQLException e)
              {
mLogger.error(new StringBuffer("SQLException while trying to closeStatement in DBAccess: "));
throw new BusinessException("SQLException while trying to closeStatement in DBAccess: " + e.getMessage(), e.getStackTrace());
}
}
/** * This function is used to close the resultset. * @param pResultSet */
public static void closeResultSet(ResultSet pResultSet) throws BusinessException
          {
try
                      {
                       if (pResultSet != null)
                              {
                          pResultSet.close();
pResultSet = null; }
}
                     catch (SQLException e)
                     {
mLogger.error(new StringBuffer("SQLException while trying to closeResultSet in DBAccess: "));
e.printStackTrace();
throw new BusinessException("SQLException while trying to closeResultSet in DBAccess: " + e.getMessage(), e.getStackTrace());
} }
public static void main(String[] args) { DBConnection.getConnection(); } }

No comments: