+ All Categories
Home > Documents > JDBC Programming Examples

JDBC Programming Examples

Date post: 27-Apr-2015
Category:
Upload: rbharath2009
View: 289 times
Download: 0 times
Share this document with a friend
28
/* ================================ JDBC Programming Examples ================================ Author: Hemanth. Balaji -------------------------- 1. Substitute your driver's JDBC URL for the generic JDBC URL that appears in the code. In other words, put your driver's JDBC URL between the quotation marks in the follwoing line: String url = "jdbc:mySubprotocol:myDataSource"; The documentation for your driver should give you this URL. 2. Substitute the driver's full class name for "myDriver.ClassName" in the following line: Class.forName("myDriver.ClassName"); 3. Substitute the username and password you use for your database in the following: "userid", "password" */ import javax.swing.JOptionPane; import java.sql.*; public class JdbcDemo { public static void main(String args[]) { JOptionPane.showMessageDialog(null,"Welcome to JDBC Demo"); int choice = -1; String userid="scott"; String password = "tiger"; do { choice = getChoice(); if (choice != 0) { getSelected(choice, userid, password);
Transcript
Page 1: JDBC Programming Examples

/* ================================JDBC Programming Examples================================

Author: Hemanth. Balaji--------------------------

1. Substitute your driver's JDBC URL for the generic JDBC URL that appears in the code. In other words, put your driver's JDBC URL between the quotation marks in the follwoing line:

String url = "jdbc:mySubprotocol:myDataSource";

The documentation for your driver should give you this URL.

2. Substitute the driver's full class name for "myDriver.ClassName" in the following line:

Class.forName("myDriver.ClassName");

3. Substitute the username and password you use for your database in the following:

"userid", "password"

*/

import javax.swing.JOptionPane;import java.sql.*;public class JdbcDemo{

public static void main(String args[]){

JOptionPane.showMessageDialog(null,"Welcome to JDBC Demo");

int choice = -1;String userid="scott";String password = "tiger";

do{

choice = getChoice();if (choice != 0){

getSelected(choice, userid, password);}

}while ( choice != 0);System.exit(0);

}

public static int getChoice(){

String choice;int ch;

Page 2: JDBC Programming Examples

choice = JOptionPane.showInputDialog(null,"1. Create Coffees Table\n"+"2. Insert Values into Coffees Table\n"+"3. Create Suppliers Table\n"+"4. Insert Values into Suppliers Table\n"+"5. Update Table Example on Coffees Table\n"+"6. A PreparedStatement Demo On Coffees Table\n"+"7. A PreparedStatement Demo On Coffees Table

using a FOR Statement\n"+"8. List of the coffees he buys from Acme, Inc

[Supplier]\n"+"9. Using Transactions Demo"+"10. Creating a Stored Procedue Demo\n"+"11. Using Callable Statement to call a Stored

Procedure\n"+"12. Batch Update Demo\n"+"0. Exit\n\n"+"Enter your choice");

ch = Integer.parseInt(choice);return ch;

}

public static void getSelected(int choice, String userid, String password)

{if(choice==1){

createCoffees(userid, password);}else if(choice==2){

insertCoffees(userid, password);}else if(choice==3){

createSuppliers(userid, password);}else if(choice==4){

insertSuppliers(userid, password);}else if(choice==5){

updateCoffees(userid, password);}else if(choice==6){

prepare1Demo(userid, password);}else if(choice==7){

prepare2Demo(userid, password);}else if(choice==8){

joinDemo(userid, password);

Page 3: JDBC Programming Examples

}else if(choice==9){

transDemo(userid, password);}else if(choice==10){

createProcedure1(userid, password);}else if(choice==11){

callableDemo(userid, password);}else if(choice==12){

batchUpdateDemo(userid, password);}

}

// Create Coffees Tablepublic static void createCoffees(String userid, String password){

String url = "jdbc:odbc:bob"; // String url = "jdbc:mySubprotocol:myDataSource"; ?

// jdbc:subprotocol:subnameConnection con;String createString;createString = "create table COFFEES " +

"(COF_NAME varchar(32), " +

"SUP_ID int, " +"PRICE float, " +"SALES int, " +"TOTAL int)";

Statement stmt;

try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//Class.forName("myDriver.ClassName"); ?

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException: ");System.err.println(e.getMessage());

}

try {con = DriverManager.getConnection(url,

"userid", "password");

stmt = con.createStatement(); stmt.executeUpdate(createString);

stmt.close();con.close();

Page 4: JDBC Programming Examples

} catch(SQLException ex) {System.err.println("SQLException: " +

ex.getMessage());}

}

// Insert values into Coffees Tablepublic static void insertCoffees(String userid, String password){

String url = "jdbc:odbc:bob";Connection con;Statement stmt;String query = "select COF_NAME, PRICE from COFFEES";

try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException: ");System.err.println(e.getMessage());

}

try {

con = DriverManager.getConnection(url,

"userid", "password");

stmt = con.createStatement();

stmt.executeUpdate("insert into COFFEES " +

"values('Colombian', 00101, 7.99, 0, 0)");

stmt.executeUpdate("insert into COFFEES " +

"values('French_Roast', 00049, 8.99, 0, 0)");

stmt.executeUpdate("insert into COFFEES " +

"values('Espresso', 00150, 9.99, 0, 0)");

stmt.executeUpdate("insert into COFFEES " +

"values('Colombian_Decaf', 00101, 8.99, 0, 0)");

stmt.executeUpdate("insert into COFFEES " +

"values('French_Roast_Decaf', 00049, 9.99, 0, 0)");

ResultSet rs = stmt.executeQuery(query);

Page 5: JDBC Programming Examples

System.out.println("Coffee Break Coffees and Prices:");

while (rs.next()) {String s =

rs.getString("COF_NAME"); // OR rs.getString(1);float f = rs.getFloat("PRICE");

// OR rs.getFloat(3);System.out.println(s + " " +

f);}

stmt.close();con.close();

} catch(SQLException ex) {System.err.println("SQLException: " +

ex.getMessage());}

}

// Create Suppliers Tablepublic static void createSuppliers(String userid, String

password){

String url = "jdbc:odbc:bob";Connection con;String createString;createString = "create table SUPPLIERS " +

"(SUP_ID int, " +"SUP_NAME varchar(40), " +"STREET varchar(40), " +"CITY varchar(20), " +"STATE char(2), ZIP

char(5))";

Statement stmt;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException:

");System.err.println(e.getMessage());

}

try {con = DriverManager.getConnection(url,

"userid", "password");

stmt = con.createStatement(); stmt.executeUpdate(createString);

stmt.close();

Page 6: JDBC Programming Examples

con.close();

} catch(SQLException ex) {System.err.println("SQLException: " +

ex.getMessage());}

}

// Insert values into Coffees Tablepublic static void insertSuppliers(String userid, String

password){

String url = "jdbc:odbc:bob";Connection con;Statement stmt;String query = "select SUP_NAME, SUP_ID from SUPPLIERS";

try {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException: ");System.err.println(e.getMessage());

}

try {con = DriverManager.getConnection(url,

"userid", "password");

stmt = con.createStatement();

stmt.executeUpdate("insert into SUPPLIERS " +

"values(49, 'Superior Coffee', '1 Party Place', " +

"'Mendocino', 'CA', '95460')");

stmt.executeUpdate("insert into SUPPLIERS " +

"values(101, 'Acme, Inc.', '99 Market Street', " +

"'Groundsville', 'CA', '95199')");

stmt.executeUpdate("insert into SUPPLIERS " +

"values(150, 'The High Ground', '100 Coffee Lane', " +

"'Meadows', 'CA', '93966')");

ResultSet rs = stmt.executeQuery(query);

System.out.println("Suppliers and their ID Numbers:");

while (rs.next()) {

Page 7: JDBC Programming Examples

String s = rs.getString("SUP_NAME");

int n = rs.getInt("SUP_ID");System.out.println(s + " " +

n);}

stmt.close();con.close();

} catch(SQLException ex) {System.err.println("SQLException: " +

ex.getMessage());}

}

// Update Coffees Tablepublic static void updateCoffees(String userid, String

password){

String url = "jdbc:odbc:bob";Connection con;String updateString;updateString = "UPDATE COFFEES " +

"SET SALES = 75 " +"WHERE COF_NAME LIKE 'Colombian'";

String query = "SELECT COF_NAME, SALES FROM COFFEES " +

"WHERE COF_NAME LIKE 'Colombian'";

Statement stmt;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException:

");System.err.println(e.getMessage());

}

try {con = DriverManager.getConnection(url,

"userid", "password");

stmt = con.createStatement();stmt.executeUpdate(updateString);

ResultSet rs = stmt.executeQuery(query);while (rs.next()) {

String s = rs.getString("COF_NAME"); //1

Page 8: JDBC Programming Examples

int n = rs.getInt("SALES"); //2

System.out.println(n + " pounds of " + s +

" sold this week.");

}

stmt.close();con.close();

} catch(SQLException ex) {System.err.println("SQLException: " +

ex.getMessage());}

}

// Update Coffees Table using a prepared Statementpublic static void prepare1Demo(String userid, String

password){

String url = "jdbc:odbc:bob";Connection con;

Statement stmt=null;String query = "SELECT COF_NAME, SALES FROM

COFFEES ";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException:

");System.err.println(e.getMessage());

}

try {con = DriverManager.getConnection(url,

"userid", "password");

PreparedStatement updateSales = con.prepareStatement(

"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");

updateSales.setInt(1, 75);updateSales.setString(2, "Colombian");updateSales.executeUpdate();

ResultSet rs = stmt.executeQuery(query);while (rs.next()) {

String s = rs.getString("COF_NAME"); //1

Page 9: JDBC Programming Examples

int n = rs.getInt("SALES"); //2

System.out.println(s + " " + n);

}

stmt.close();con.close();

} catch(SQLException ex) {System.err.println("SQLException: " +

ex.getMessage());}

}

// Update Coffees Table using a prepared Statementpublic static void prepare2Demo(String userid, String

password){

String url = "jdbc:odbc:bob";Connection con;

Statement stmt=null;String query = "SELECT COF_NAME, SALES FROM

COFFEES ";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException:

");System.err.println(e.getMessage());

}

try {con = DriverManager.getConnection(url,

"userid", "password");

PreparedStatement updateSales;String updateString = "update COFFEES " +

"set SALES = ? where COF_NAME like ?";

updateSales = con.prepareStatement(updateString);

int [] salesForWeek = {175, 150, 60, 155, 90};

String [] coffees = {"Colombian", "French_Roast", "Espresso",

"Colombian_Decaf", "French_Roast_Decaf"};

int len = coffees.length;for(int i = 0; i < len; i++) {

Page 10: JDBC Programming Examples

updateSales.setInt(1, salesForWeek[i]);

updateSales.setString(2, coffees[i]);

updateSales.executeUpdate();

// int n= updateSales.executeUpdate() to find out how may rows have been updated

}

ResultSet rs = stmt.executeQuery(query);while (rs.next()) {

String s = rs.getString("COF_NAME"); //1

int n = rs.getInt("SALES"); //2

System.out.println(s + " " + n);

}

stmt.close();con.close();

} catch(SQLException ex) {System.err.println("SQLException: " +

ex.getMessage());}

}

//Using join on 2 table to retrieve resultspublic static void joinDemo(String userid, String

password){

String url = "jdbc:odbc:bob";Connection con;String query = "select SUPPLIERS.SUP_NAME,

COFFEES.COF_NAME " + "from COFFEES,

SUPPLIERS " + "where

SUPPLIERS.SUP_NAME like 'Acme, Inc.' and " + "SUPPLIERS.SUP_ID =

COFFEES.SUP_ID";Statement stmt;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException:

");System.err.println(e.getMessage());

}

Page 11: JDBC Programming Examples

try {con = DriverManager.getConnection (url,

"userid", "password");

stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(query);System.out.println("Supplier, Coffee:");while (rs.next()) {

String supName = rs.getString(1);String cofName = rs.getString(2);System.out.println(" " +

supName + ", " + cofName);}

stmt.close();con.close();

} catch(SQLException ex) {System.err.print("SQLException: ");System.err.println(ex.getMessage());

}}

// Using Transaction Autocommit Optionpublic static void transDemo(String userid, String

password){

String url = "jdbc:odbc:bob";Connection con=null;Statement stmt;PreparedStatement updateSales;PreparedStatement updateTotal;String updateString = "update COFFEES " +

"set SALES = ? where COF_NAME = ?";

String updateStatement = "update COFFEES " +"set TOTAL = TOTAL + ? where

COF_NAME = ?";String query = "select COF_NAME, SALES, TOTAL

from COFFEES";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException:

");System.err.println(e.getMessage());

}

try {

Page 12: JDBC Programming Examples

con = DriverManager.getConnection(url,

"userid", "password");

updateSales = con.prepareStatement(updateString);

updateTotal = con.prepareStatement(updateStatement);

int [] salesForWeek = {175, 150, 60, 155, 90};

String [] coffees = {"Colombian", "French_Roast",

"Espresso", "Colombian_Decaf",

"French_Roast_Decaf"};

int len = coffees.length;con.setAutoCommit(false);for (int i = 0; i < len; i++) {

updateSales.setInt(1, salesForWeek[i]);

updateSales.setString(2, coffees[i]);

updateSales.executeUpdate();

updateTotal.setInt(1, salesForWeek[i]);

updateTotal.setString(2, coffees[i]);

updateTotal.executeUpdate();con.commit();

}

con.setAutoCommit(true);

updateSales.close();updateTotal.close();

stmt = con.createStatement();ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {String c =

rs.getString("COF_NAME");int s = rs.getInt("SALES");int t = rs.getInt("TOTAL");System.out.println(c + " " +

s + " " + t);}

stmt.close();con.close();

} catch(SQLException ex) {System.err.println("SQLException: " +

ex.getMessage());if (con != null) {

Page 13: JDBC Programming Examples

try {

System.err.print("Transaction is being ");System.err.println("rolled

back");con.rollback();

} catch(SQLException excep) {

System.err.print("SQLException: ");

System.err.println(excep.getMessage());}

}}

}

/*Creating a Stored procedure involving the coffees and the suppliers table

create procedure SHOW_SUPPLIERSasselect SUPPLIERS.SUP_NAME,

COFFEES.COF_NAMEfrom SUPPLIERS, COFFEESwhere SUPPLIERS.SUP_ID =

COFFEES.SUP_IDorder by SUP_NAME

*/

public static void createProcedure1(String userid, String password)

{String url = "jdbc:odbc:bob";Connection con;Statement stmt;String createProcedure = "create procedure

SHOW_SUPPLIERS " + "as " + "select

SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from SUPPLIERS, COFFEES

" + "where SUPPLIERS.SUP_ID =

COFFEES.SUP_ID " + "order by SUP_NAME";

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());}

Page 14: JDBC Programming Examples

try {con =

DriverManager.getConnection(url,

"DPST_TRNG", "DPST_TRNG4321");

stmt = con.createStatement();stmt.executeUpdate(createProcedure);stmt.close();con.close();

} catch(SQLException ex) {System.err.println("SQLException:

" + ex.getMessage());}

}

//Using Callable Statement to call a Stored Procedurepublic static void callableDemo(String userid, String

password){

String url = "jdbc:odbc:bob";Connection con;Statement stmt=null;

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {

System.err.print("ClassNotFoundException: ");

System.err.println(e.getMessage());}

try {con =

DriverManager.getConnection(url,

"DPST_TRNG", "DPST_TRNG4321");

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

ResultSet rs = cs.executeQuery();

while (rs.next()) {String c =

rs.getString("SUP_NAME");String s =

rs.getString("COF_NAME");System.out.println(c + "

" + s );}

Page 15: JDBC Programming Examples

stmt.close();con.close();

} catch(SQLException ex) {System.err.println("SQLException:

" + ex.getMessage());}

}

//A code showing the Batch Update Syntaxpublic static void batchUpdateDemo(String userid, String

password){

ResultSet rs = null;PreparedStatement ps = null;

String url = "jdbc:odbc:bob";

Connection con;Statement stmt;try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {System.err.print("ClassNotFoundException:

");System.err.println(e.getMessage());

}

try {

con = DriverManager.getConnection(url,"us

erid", "password");con.setAutoCommit(false);

stmt = con.createStatement();

stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0,

0)");stmt.addBatch("INSERT INTO COFFEES " +

"VALUES('Hazelnut', 49, 9.99, 0, 0)");

stmt.addBatch("INSERT INTO COFFEES " +"VALUES('Amaretto_decaf', 49,

10.99, 0, 0)");stmt.addBatch("INSERT INTO COFFEES " +

"VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)");

int [] updateCounts = stmt.executeBatch();

con.commit();con.setAutoCommit(true);

Page 16: JDBC Programming Examples

ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");

System.out.println("Table COFFEES after insertion:");

while (uprs.next()) {String name =

uprs.getString("COF_NAME");int id = uprs.getInt("SUP_ID");float price =

uprs.getFloat("PRICE");int sales = uprs.getInt("SALES");int total = uprs.getInt("TOTAL");System.out.print(name + " " +

id + " " + price);System.out.println(" " + sales

+ " " + total);}

uprs.close();stmt.close();con.close();

} catch(BatchUpdateException b) {System.err.println("-----

BatchUpdateException-----");System.err.println("SQLState: " +

b.getSQLState());System.err.println("Message: " +

b.getMessage());System.err.println("Vendor: " +

b.getErrorCode());System.err.print("Update counts: ");int [] updateCounts =

b.getUpdateCounts();for (int i = 0; i < updateCounts.length;

i++) {System.err.print(updateCounts[i]

+ " ");}System.err.println("");

} catch(SQLException ex) {System.err.println("-----

SQLException-----");System.err.println("SQLState: " +

ex.getSQLState());System.err.println("Message: " +

ex.getMessage());System.err.println("Vendor: " +

ex.getErrorCode());}

}

}//End of class

Page 17: JDBC Programming Examples

Connect to a database via JDBC-ODBC

You have to keep in mind that the bridge JDBC-ODBC is only useful in an Application, you can't use it with

JAVA Applet because ODBC requires some DLL on the client machine (forbidden for security reason).

import java.net.URL;

import java.sql.*;

class JDBCapp {

static Connection theConn;

public static void main (String args[]) {

try {

// connection to an ACCESS MDB

theConn = MyConnection.getConnection();

ResultSet rs;

Statement stmt;

String sql;

sql = "select objet from Email";

stmt = theConn.createStatement();

rs = stmt.executeQuery(sql);

while (rs.next()) {

System.out.println(rs.getString("objet"));

}

rs.close();

stmt.close();

}

catch (Exception e) {

e.printStackTrace();

}

finally {

Page 18: JDBC Programming Examples

try {

if (theConn != null) theConn.close();

}

catch (Exception e) {

}

}

}

}

class MyConnection {

public static Connection getConnection() throws Exception {

Driver d = (Driver)Class.forName

("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

Connection c = DriverManager.getConnection(

"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/tech97.mdb"

);

return c;

/*

To use an already defined ODBC Datasource :

String URL = "jdbc:odbc:myDSN";

Connection c = DriverManager.getConnection(URL, "user", "pwd");

*/

}

}

JDBC (Java Database Connectivity) -Tutorials                          

Introduction to JDBC

Java started as an elegant and promising Web programming language. Thereafter, its transition to hard-core computing environment is a phenomenal feat. Apart from its significance on client-side programming, Java has been outstanding in developing mission-critical enterprise-scale applications and hence its immense contribution to server-side computing gets all round attention. Thus Java as a programming language

Page 19: JDBC Programming Examples

for enterprise computing has been doing well for the past couple of years. As every enterprise includes a database, Sun Microsystems has to come with necessary features for making Java to shine in database programming as well. In this overview, we discuss about the role of Java Database Connectivity in accomplishing database programming with ease.

Database Programming with Java

Java provides database programmers some distinct advantages, such as easy object to relational mapping, database independence and distributed computing. For languages, such as C++ and Smalltalk, there is a need for tools for mapping their objects to relational entities. Java provides an alternative to these tools that frees us from the proprietary interfaces associated with database programming. With the "write once, compile once, run anywhere" power that JDBC offers us, Java's database connectivity allows us to concentrate on the translation of relational data into objects instead of how we can get that data from the database.

A Java database application does not care what its database engine is. No matter how many times the database engine changes, the application itself need never change. In addition, a company can build a class library that maps its business objects to database entities in such a way that applications do not even know whether or not their objects are being stored in a database.

Java affects the way we distribute and maintain application. Currently a Web application allows user to download a bunch of flight information as an HTML page. While viewing the page for a particular flight, suppose some one makes a reservation for a seat on that flight and this process will not be available to the viewers as the page is just a copy of data from the database. To view the change that just occurred, the viewers again have to contact the database to get the latest data. If we reconstruct the same Web application using Java RMI to retrieve the data from a single flight object on the server, any number of users can view the data simultaneously and if there is any reservation or any change taking place, immediately the changes made to the data will be sent back to all the users and hence the users can avail the latest data at any time. Thus JDBC can combine with Java RMI to develop distributed enterprise-scale mission-critical three-tier database applications.

JDBC for Relational Databases

There are three main database technologies. They are relational, object and object-relational. A Java application can access any one of these database architectures. The overwhelming majority of today's database applications use relational databases. The JDBC API is thus heavily biased toward relational databases and their standard query language, SQL. Relational databases find and provide relationships between data and Java, as a object solution makes common cause with relational database technology due to the fact that object-oriented philosophy dictates that an object's behavior is inseparable from its data. In choosing the object-oriented reality of Java, we need to create a translation layer that maps the relational world into our object world. Thus with the goal of accessing relational databases, JDBC API specification has been defined by Sun Microsystems with the help of popular database vendors.

Page 20: JDBC Programming Examples

What is JDBC?

JDBC is essentially an Application Programming Interface (API) for executing SQL statements, and extracting the results. Using this API, we can write database clients, such as Java applets, servlets and Enterprise JavaBeans, that connect to a relational database, such as Oracle, MySQL, Sybase, Informix, Ingres, PostgreSQL, or any other database that implements this API, execute SQL statements, and process the results extracted from the database.

JDBC Versions

JDBC 2.0 API is the latest version of JDBC API available in the java.sql package. The previous version focused primarily on basic database programming services such as creating connections, executing statements and prepared statements, running batch queries, etc. However, the current API supports batch updates, scrollable resultsets, transaction isolation, and the new SQL:1999 data types such as BLOB and CLOB in addition to the SQL2 data types.

JDBC 2.0 Optional Package API is available in the javax.sql package and is distributed with the enterprise edition of Java 2, that is J2EE. The optional package addresses Java Naming and Directory Interface (JNDI)-based data sources for managing connections, connection pooling, distributed transactions, and rowsets.

The Benefits of JDBC

The JDBC API provides a set of implementation-independent generic database access methods for the above mentioned SQL-compliant databases. JDBC abstracts much of the vendor-specific details and generalizes the most common database access functions. Thus resulted a set of classes and interfaces of the java.sql package that can be used with any database providing JDBC connectivity through a vendor-specific JDBC driver in a consistent way. Thus if our application conforms to the most commonly available database features, we should be able to reuse an application with another database simply by switching to a new JDBC driver. In other words, JDBC enables us to write applications that access relational databases without any thought as to which particular database we are using.

Also database connectivity is not just connecting to databases and executing statements. In an enterprise-level application environment, there are some important requirements to be met, such as optimizing network resources by employing connection pooling, and implementing distributed transactions. JDBC has all these features in accomplishing advanced database programming.

The JDBC Drivers

A database vendor typically provides a set of APIs for accessing the data managed by the database server. Popular database vendors have supplied some proprietary APIs for client access. Client applications written in native languages such as C and C++ can make these API calls for database access directly. The JDBC API provides a Java-language alternative to these vendor-specific APIs. Though this takes away the need to access vendor-specific native APIs for database access, the implementation of the JDBC layer still need to make these native calls for data access.

Page 21: JDBC Programming Examples

JDBC accomplishes its goals through a set of Java interfaces, each gets implemented differently by different vendors. The set of classes that implement the JDBC interfaces for a particular database engine is called a JDBC driver. Hence the necessity of a JDBC driver for each database server. In building a database application, we do not have to think about the implementation of these underlying classes at all as the whole point of using JDBC is to hide the specifics of each database and let us concentrate on our application. A JDBC driver is a middleware layer that translates the JDBC calls to the vendor-specific APIs. The Java VM uses the JDBC driver to translate the generalized JDBC calls into vendor-specific database calls that the database understands.

There are a number of approaches for connecting from our application to a database server via a database driver.

JDBC-ODBC Bridge - Open Database Connectivity (ODBC) was developed to create a single standard for database access in the Windows environment. ODBC is a Windows API standard for SQL and it is based on X/Open Call-Level Interface (CLI) specification, which is a standard API for database access. CLI is intended to be vendor, platform, and database neutral. But ODBC API defines a set of functions for directly accessing the data without the need for embedding SQL statements in client applications coded in higher level languages.

The JDBC API is originally based on the ODBC API. Thus, it becomes feasible for the first category of JDBC drivers providing a bridge between the JDBC API and the ODBC API. This bridge translates the standard JDBC calls to corresponding ODBC calls. The driver then delegates these calls to the data source. Here, the Java classes for the JDBC API and the JDBC-ODBC bridge are invoked within the client application process. Similarly, the ODBC layer executes in another process. This configuration requires the client application to have the JDBC-ODBC bridge API, the ODBC driver, and the native language level API, such as the OCI library for Oracle installed on each client machine.

Each data access call has to go through many layers, this approach for data access is inefficient for high-performance database access requirements. Though this is not a preferred one, this has to be used in some situations for example, a Microsoft Access 2000 database can be only be accessed using the JDBC-ODBC bridge.

Part Java, Part Native Driver - This approach use a mixture of Java implementation and vendor-specific native APIs for data access. This one is a little bit faster than the earlier one. When a database call is made using JDBC, the driver translates the request into vendor-specific API calls. The database will process the request and send the results back through the API, which will forward them back to the JDBC driver. The JDBC driver will format the results to confirm to the JDBC standard and return them to the program. In this approach, the native JDBC driver, which is part Java and part native code, should be installed on each client along with the vendor-specific native language API. The native code uses vendor-specific protocols for communicating with the database. The improved efficiency makes this a preferred method over the use of the earlier one.

Page 22: JDBC Programming Examples

Intermediate Database Access Server This approach is based on intermediate (middleware) database servers with the ability to connect multiple Java clients to multiple database servers. In this configuration, clients connect to various database servers via an intermediate server that acts as a gateway for multiple database servers. While the specific protocol used between clients and the intermediate server depends on the middleware server vendor, the intermediate server can use different native protocols to connect to different databases. The Java client application sends a JDBC call through a JDBC driver to the intermediate data access server. The middle-tier then handles the request using another driver, for example the above one, to complete the request. This is good because the intermediate server can abstract details of connections to database servers.

Pure Java Drivers - This a pure Java alternative to part Java, part native driver. These drivers convert the JDBC API calls to direct network calls using vendor-specific networking by making direct socket connections with the database like Oracle Thin JDBC Driver. This is the most efficient method of accessing databases both in performance and development time. It also the simplest to deploy since there are no additional libraries or middleware to install. All major database vendors, such as Oracle, Sybase, and Microsoft, provide this type of drivers for their databases.

Alternatives to JDBC

There are two major alternatives to JDBC at present. They are ODBC and SQLJ, a non-approved Java standard for database access.

Without JDBC, only disparate, proprietary database access solutions exist. These solutions force the developer to build a layer of abstraction on top of them in order to create database-independent code. The ODBC solution provide this universal abstraction layer for languages, such as C and C++, and popular developmental tools, such as Delphi, PowerBuilder, and VisualBasic. But ODBC can not enjoy the platform independence of Java as ODBC is restricted to Windows platform. On using JDBC, the server application can pick the database at run time based on which client is connecting. Thus JDBC facilitates to change the database just by changing the JDBC URL and driver name without adding any new code.

Many of the major database vendors have designed SQLJ through joint work. SQLJ is a specification for writing embedded SQL in Java applications that a preprocessor can read and turn into JDBC calls.


Recommended