Tuesday, 16 September 2014

JDBC Basics – Java Database Connectivity Steps

Before you can create a java Jdbc connection to the database, you must first import the
java.sql package.
import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be imported.



1. Loading a database driver


In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. 

Once loaded, the Driver class creates an instance of itself. 

A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.

The return type of the Class.forName (String ClassName) method is “Class”. Class is a class in java.lang package.

For full JDBC Tutorial : JDBC tutorial

try {
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
}
catch(Exception x){
System.out.println( “Unable to load the driver class!” );
}

With JDBC we need to handle exception . As in the above example we are handling exception if its unable to load the driver class.For more Information on Exception read Exception Handling in JAVA


2.Creating a oracle jdbc Connection




The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. 

DriverManager is considered the backbone of JDBC architecture.

DriverManager class manages the JDBC drivers that are installed on the system.

Its getConnection() method is used to establish a connection to a database.

It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object.

A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned.

An application can have one or more connections with a single database, or it can have many connections with different databases.

A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions.

JDBC URL Syntax::    jdbc: <subprotocol>: <subname>
JDBC URL Example:: jdbc: <subprotocol>: <subname>


Each driver has its own subprotocol
•Each subprotocol has its own syntax for the source. We’re using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.



try{
 Connection dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}

catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}


3. Creating a jdbc Statement object

Once a connection is obtained we can interact with the database.
Connection interface defines methods for interacting with the database via the established connection.
To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method.

Statement statement = dbConnection.createStatement();

A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements:

1. Simple Statement 
2. Prepared Statement
3. PreparedStatement


For more information on Statements see :JDBC statements


4. Executing a SQL statement 


This we will demonstrate with the Statement object, and returning a jdbc resultSet. 

Statement interface defines methods that are used to interact with database via the execution of SQL statements. 

The Statement class has three methods for executing statements:
executeQuery(), 
executeUpdate(),
 and execute(). 

For a SELECT statement, the method to use is executeQuery
For statements that create or modify tables, the method to use is executeUpdate
Note: Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. execute() executes an SQL
statement that is written as String object.

Before going further we need to know about ResultSet .


ResultSet in JDBC


ResultSet provides access to a table of data generated by executing a Statement. 

The table rows are retrieved in sequence.

 A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results.

ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. 

It is constructed from the Connection object.

See :How to sort an Array List without using Comparator or sort method
5. Test JDBC Driver Installation

import javax.swing.JOptionPane;

public class TestJDBCDriverInstallation_Oracle {

  public static void main(String[] args) {
 StringBuffer output  = new StringBuffer();
 output.append(”Testing oracle driver installation \n”);
 try {
 String className = “sun.jdbc.odbc.JdbcOdbcDriver”;
 Class driverObject = Class.forName(className);
 output.append(”Driver : “+driverObject+”\n”);
 output.append(”Driver Installation Successful”);
 JOptionPane.showMessageDialog(null, output);
   } catch (Exception e) {
    output  = new StringBuffer();
    output.append(”Driver Installation FAILED\n”);
    JOptionPane.showMessageDialog(null, output);
  System.out.println(”Failed: Driver Error: ” + e.getMessage());
 }
   }
}





No comments:

Post a Comment