JDBC Database Connections

JDBC Database Connections

After you've installed the appropriate driver, it's time to establish a database connection using JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps:
·         Import JDBC Packages: Add import statements to your Java program to import required classes in your Java code.
·         Register JDBC Driver: This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests.
·         Database URL Formulation: This is to create a properly formatted address that points to the database to which you wish to connect.
·         Create Connection Object: Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection.

Import JDBC Packages:

The Import statements tell the Java compiler where to find the classes you reference in your code and are placed at the very beginning of your source code.
To use the standard JDBC package, which allows you to select, insert, update, and delete data in SQL tables, add the following imports to your source code:
import java.sql.* ;  // for standard JDBC programs
import java.math.* ; // for BigDecimal and BigInteger support

Register JDBC Driver:

You must register the your driver in your program before you use it. Registering the driver is the process by which the Oracle driver's class file is loaded into memory so it can be utilized as an implementation of the JDBC interfaces.
You need to do this registration only once in your program. You can register a driver in one of two ways.

Approach (I) - Class.forName():

The most common approach to register a driver is to use Java's Class.forName() method to dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable.
The following example uses Class.forName( ) to register the Oracle driver:
try {
   Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
   System.out.println("Error: unable to load driver class!");
   System.exit(1);
}
You can use getInstance() method to work around noncompliant JVMs, but then you'll have to code for two extra Exceptions as follows:
try {
   Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
   System.out.println("Error: unable to load driver class!");
   System.exit(1);
catch(IllegalAccessException ex) {
   System.out.println("Error: access problem while loading!");
   System.exit(2);
catch(InstantiationException ex) {
   System.out.println("Error: unable to instantiate driver!");
   System.exit(3);

}

Post a Comment

Previous Post Next Post