Java Database Connectivity

advertisement
Java Database Connectivity
Contents
Overview of JDBC
JDBC configuration
Connections
Querying the database
JDBC Interfaces
Architecture
Examples
Overview of JDBC
Originally, Java only provided file system access, with no provisions for database access. In
February 1996, JavaSoft, an operating company of Sun Microsystems, started to address the need
for database access with the draft release of the Java Database Connectivity (JDBC)
specification. With support from a number of independent software vendors, Sun developed a
JDBC that would provide a common base API for accessing data.
The Internet's World Wide Web allows businesses and consumers to access unstructured data.
Currently, it does not allow access to data stored in conventional databases. This API extends the
Web by allowing embedded Java applications to access such data. JDBC has a number of Java
interfaces that allow developers to access data independently of the actual database being used to
store the data. The goal is to allow applications that are written in basic JDBC API using only
SQL-2 to work with any database technology that supports SQL-2. Basically, JDBC is a vehicle
for using SQL-2 to interact with any SQL-2 server running in the back-end. Because JDBC
isolates the database access behind a single interface, the isolation allows developers to write
database accesses in Java without having to know which database engine their application is
actually located in.
JDBC is an attempt to define a generic SQL database access framework. The JDBC API is based
on the X/Open SQL Call Level Interface specification. JDBC drivers can be written in Java so
they can be downloaded as part of an applet.
Traditionally client/server systems have been implemented using the two-tier approach. In JDBC
a two-tier architecture is one in which a Java applet or application on a client machine talks
directly to a server. The three-tier model moves some of the application logic from the client
workstation onto an application server. Three-tier architecture can provide performance
advantages over two-tier implementations.
1
JDBC configuration
Database drivers provide implementations of the interfaces provided by the JDBC API.
JDBC drivers fit into one of four categories:
the
the
the
the
JDBC-ODBC bridge driver
native-API partly-Java driver
JDBC-net all-Java driver
native-protocol all-Java driver
The DriverManager class is responsible for loading class drivers and provides support for
creating new database connections. In the three-tier database access model, Java applications
send calls to a middle tier of services on the Net.
Overall architecture and JDBC - ODBC bridge
2
Connections
A connection to a database is established through the Connection object by calling the
DriverManager.getConnection method. The argument for this method is a URL string and takes
the following format:
string url = jdbc:subprotocol:subname". Subprotocol names can be
reserved for a particular driver. For example, the subprotocol odbc is reserved for the JDBCODBC bridge driver and has the following syntax:
jdbc:odbc:data-source-name
[;attribute-name=attribute-value]*
The subname contains more specific details about the location of the resource. Connection
arguments are passed in the form of a JDBC URL string to open a database. The processing that
is carried out by JDBC is synchronous. The driver you are using determines the degree of
process concurrency.
Querying the database
Statement objects are created to send SQL statements. The methods used to create them are part
of the Connection interface. The Statement object is used to send simple SQL statements with no
parameters. The PreparedStatement object is responsible for sending pre-compiled SQL
statements containing parameters with input arguments.
The CallableStatement object sends SQL statements to procedures stored in a database and it
handles IN, OUT, and INOUT parameters.
The Statement interface produces three methods for executing statements:
executeQuery
executeUpdate
execute
Escape syntax included in statements indicates to the driver that the code needs to be translated
before passing it to the database. A transaction is one or more statements that have been executed
and completed, and then either committed or rolled back. You can specify a transaction isolation
level to help minimize error and disruption. The ResultSet interface defines methods that allow
you to retrieve data returned from the execution of a statement. Result sets are generally returned
in the form of a table. A number of "get" methods are used to access values stored in tables of
data. To create an applet to query a database you must
load the appropriate driver
create a SQL query string
call the Connection method
create and execute a query
DriverManager.getConnection
3
The JDBC Interfaces
In order to be JDBC compliant, the driver must be able to implement the following nine
interfaces.
1. java.sql.DriverManager
2. java.sql.Driver
3. java.sql.Connection
4. java.sql.Statement
5. java.sql.PreparedStatement
6. java.sql.CallableStatement
7. java.sql.ResultSet
8. java.sql.ResultSetMetaData
9. java.sql.DatabaseMetaData
All the interfaces revolve around the DriverManager. DriverManager is responsible for keeping
track of the various JDBC implementations that could exist for an application. If, for example, a
system is being used by Sybase or Oracle JDBC implementations, the DriverManager will be
responsible for keeping track of those implementations. When an application wants to connect to
a database, it will asked the DriverManager to give it a database connection by using a database
URL through the DriverManager.getConnection() method. Based on this URL, the
DriverManager will search for a Driver implement that will accept the URL. Once it get a
Connection implement from that Driver, it will return it to the application.
The Driver handles the connection. The Driver is used by the DriverManager to determine
whether it can handle a given URL. If one of the Drivers in DriverManager’s list can handle the
URL, that Driver will create a Connection object and return it to the DriverManager.
The Connection will be a single database session. Therefore, it will only store state information
about that database session it manages. The Connection will also provide the application with
Statement, PreparedStatement, or CallableStatement objects for making calls during the session
The Statement is the SQL call to the database. UPDATE, DELETE, INSERT, or SELECT are
the common statements. These statements do not require columns to be bound to Java data. The
Statement allows methods to make calls and return to the application the results of the statement
or the number of rows affected by an UPDATE, DELETE, or INSERT statement .
PreparedStatement is a subclass of Statement. PreparedStatement is a precompiled database call
and parameters are required in PreparedStatement. CallableStatement interface is a subclass of
PreparedStatement .
An application will receive the data by a SELECT query through the implementer of
java.sql.ResultSet interface. The ResultSet object will allow an application to retrieve sequential
rows of data that are returned from a previous SELECT call. The ResultSet contain methods that
allow you to retrieve a given row as any data type and the data can be converted later on. For
example, you store a date in the database as a datetime, and you can retrieve the data through a
method called getString() and use it as a String data type .
The Meta-data interfaces are a set of data that give you information on the database and data
retrieved from the database. ResultSetMetaData interface allow you to get information about a
4
particular ResultSet. For example, it provides information on the number of columns in the result
set, the name of the column, and its type. On the other hand, DatabaseMetaData provides the
application information on the database, such as what level of support it has, its name, and
version .
An illustration of a simple database access using the JDBC interfaces would involve the
following steps. First, the database application must ask the DriverManager for a Connection
implementation. Then it would ask the Connection for a Statement or subclass of Statement to
execute your SQL. In the subclasses of Statement, you will need to bind any parameters to be
passed to the prepared statement. The program will execute the statement. If the statement was a
query, the program will process the result set returned from the query and repeat each result set
until there are none left. If the statement is another type, the program will check the return value
for the number of rows affected. After completing all the statement, the program will close it,
and close the connection .
The JDBC API is implemented by driver manager that can support multiple drivers connecting to
different databases. JDBC drivers can either be entirely written in Java so that they can be
downloaded as part of an applet, or they can be implemented using native methods to bridge to
existing database access libraries. Some companies prefer to use the Bridge because ODBC is
already being used on the Windows platform. This "layer" which translates all JDBC calls to and
from ODBC calls works well on any Windows machine. The bridge driver translates JDBC
method calls into ODBC function calls. It allows JDBC to leverage the database connectivity
provided by the existing array of ODBC drivers. JDBC is designed to be capable of being
implemented on ODBC. There are some disadvantages of using the JDBC-ODBC Bridge Driver.
The right ODBC drivers must be installed locally, and there has to be a .DLL (windows dynamic
link library) file installed on the local machine before it can interface with the ODBC drivers
locally. It contradict the idea of platform independence. This strategy is more of a short term
solution by allowing programs to use JDBC now, while maintaining an ODBC back end. If the
ODBC layer was done in Java then most of the problems of platform independence would
dissapear, but if the company is going to implement ODBC in Java, they should just implement
JDBC in Java and the problem wouldn’t exist.
The pure JDBC is more of a long term solution strategy. Many softwware companies
implemented the JDBC interface for their database products and also wrote drivers to access
their databases in Java itself. Unlike the ODBC "bridge" solution, this is a 100% Java
implementation. It will take the company more time to do than the Bridge but it's a cleaner
solution . The advantages of this strategy are the following:
1. It allows the use of "thin-clients". This means that clients DO NOT have to have any drivers
for any of the database stuff installed locally. When the client needs to access the database, this
JDBC layer implementation takes care of sending the right drivers over the client.
2. This is a very attractive solution for companies that want to keep things very platform
independent. The companies don't have to install any OS/machine specfic stuff before hand.
3. Easy to change the backend. The company can change the backend database server at anytime
and the clients will NOT know the difference. They don't have to worry about updating the right
drivers on the clients, since the drivers are downloaded on the fly! This is one of the promises of
Java.
5
Examples
Example of a Select command. It was taken from
(http://konark.ncst.ernet.in/~javainfo/lectures/jdbc/Simplet_pre.html).
import connect.sql.*;
import java.awt.Graphics;
import java.util.Properties;
public class Simplet extends java.applet.Applet {
public void init() {
resize(600,425); }
public void paint(Graphics g) {
try {
// Connect to the database at that URL.
String url = "jdbc:sybase://144.16.1.246:2000";
Properties props = new Properties();
props.put("user", "sudhinp");
props.put("password", "");
Driver driver = null;
// load the driver
driver = (Driver) Class.forName("sybase.sql.SybaseDriver").newInstance();
// Get a connection
Connection con = driver.connect(url, props);
// Create a Statement object to hold sql statments and execute them
Statement stmt = con.createStatement();
// retrieve data from database
ResultSet rs = stmt.executeQuery("SELECT course_id,course_desc FROM course");
g.drawString("Let's retrieve some data from the database...", 10, 10);
g.drawString("Received results:", 10, 25);
// display the result set
g.drawString("course_id course_desc", 20, 45);
g.drawString("--------- -----------", 20, 55); int y = 80;
// rs.next() returns false when there are no more rows
while (rs.next() ) {
String c1= rs.getString(1);
String c2 = rs.getString(2); g.drawString(c1, 20, y );
g.drawString(c2, 100, y );
y = y + 15;
}
stmt.close();
con.close(); }
catch( Exception e ) {
e.printStackTrace();
}
}
6
}
import connect.sql.*;
import java.awt.Graphics;
import java.util.Properties;
public class Update extends java.applet.Applet {
public void init() {
resize(600,425);
}
public void paint(Graphics g) {
try {
// Connect to the database at that URL.
Driver driver = null;
int row_count = 0;
String url = "jdbc:sybase://144.16.1.246:2000";
Properties props = new Properties();
props.put("user", "sudhinp");
props.put("password", "");
// register the driver with DriverManager
driver = (Driver) Class.forName("sybase.sql.SybaseDriver").newInstance();
Connection con = driver.connect(url, props);
// retrieve data from database
g.drawString("Let's update a row", 10, 10);
// The prepared statement takes two parameters.
PreparedStatement stmt = con.prepareStatement( "UPDATE course SET course_desc = ?
WHERE course_id = ?");
// First use the prepared statement to update stmt.setString(1, "NETWORKS WORKSHOP");
stmt.setString(2, "CNET");
row_count = stmt.executeUpdate();
g.drawString("Number of rows affected : "+row_count, 10, 25);
System.out.println("Updated \"count\" row OK.");
stmt.close();
con.close();
} catch (java.lang.Exception ex) {
ex.printStackTrace();
}
}
}
7
Work Cited
1. Morrison, Michael, Java Unleashed 2nd Edition. Indianapolis, IN: Sams.net Publishing,
pp.637-653.
2. Lemay, Laura and Perkins, Charles, Teach Yourself JAVA in 21 Days. Indianapolis, IN:
Sams.net Publishing, . 1-45.
3. http://konark.ncst.ernet.in/~javainfo/lectures/jdbc/Simplet_pre.html
You can learn more about the java applet from the following sites.
Sun Microsystems Java Java's official home page.
Gamelan A directory and registry of Java Applets on the web.
JARS A Java Applet rating service.
Digital Cats' Java Resource Center A large bi-lingual Java resource center.
Cafe del Sol has many great java applets
Yahoo's Java Directory A catalogue of Java resources.
8
Download