![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]()
![]()
(chat, newsreader, calendar)
|
![]() |
|
Course Notes Table of Contents | Exercises JDBC Short Course Index | Online Training Index
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Java Database Programming | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
In this course, you will learn:
Introduction to JDBCSQL is a language used to create, manipulate, examine, and manage relational databases. Because SQL is an application-specific language, a single statement can be very expressive and can initiate high-level actions, such as sorting and merging data. SQL was standardized in 1992 so that a program could communicate with most database systems without having to change the SQL commands. Unfortunately, you must connect to a database before sending SQL commands, and each database vendor has a different interface, as well as different extensions of SQL. Enter ODBC.ODBC, a C-based interface to SQL-based database engines, provides a consistent interface for communicating with a database and for accessing database metadata (information about the database system vendor, how the data is stored, and so on). Individual vendors provide specific drivers or "bridges" to their particular database management system. Consequently, thanks to ODBC and SQL, you can connect to a database and manipulate it in a standard way. It is no surprise that, although ODBC began as a PC standard, it has become nearly an industry standard. Though SQL is well suited for manipulating databases, it is unsuitable as a general application language and programmers use it primarily as a means of communicating with databases--another language is needed to feed SQL statements to a database and process results for visual display or report generation. Unfortunately, you cannot easily write a program that will run on multiple platforms even though the database connectivity standardization issue has been largely resolved. For example, if you wrote a database client in C++, you would have to totally rewrite the client for each platform; that is to say, your PC version would not run on a Macintosh. There are two reasons for this. First, C++ as a language is not portable for the simple reason that C++ is not completely specified, for example, how many bits does an int hold? Second and more importantly, support libraries such as network access and GUI libraries are different on each platform. Enter Java. You can run a Java program on any Java-enabled platform without even recompiling that program. The Java language is completely specified and, by definition, a Java-enabled platform must support a known core of libraries. One such library is JDBC, which you can think of as a Java version of ODBC, and is itself a growing standard. Database vendors are already busy creating bridges from the JDBC API to their particular systems. JavaSoft has also provided a bridge driver that translates JDBC to ODBC, allowing you to communicate with legacy databases that have no idea that Java exists. Using Java in conjunction with JDBC provides a truly portable solution to writing database applications. The JDBC-ODBC bridge driver is just one of four types of drivers available to support JDBC connectivity. It comes packaged with the JDK 1.1 (and eventually with 1.1 browsers), or as a separate package for use with 1.0 systems. A Complete ExampleRunning through a simple, but complete, example will help you grasp the overall concepts of JDBC. The fundamental issues encountered when writing any database application are:
Creating a DatabaseFor this example, consider the scenario of tracking coffee usage at the MageLang University Cafe. A weekly report must be generated for University management that includes total coffee sales and the maximum coffee consumed by a programmer in one day. Here is the data:
"Caffeinating the World, one programmer at a time"
To create this database, you can feed SQL statements to an ODBC data source via the JDBC-ODBC bridge. First, you will have to create an ODBC data source. You have many choices--you could, for example, connect an Oracle or Sybase database. For simplicity and to cover the largest single audience, create a text file as an ODBC datasource to use for this example. Call this ODBC data source CafeJolt. To enter the data into the CafeJolt database, create a Java application that follows these steps:
Review what you have done so far. After creating a data source visible to ODBC,
you connected to that source via the JDBC-ODBC bridge and sent a series of SQL
statements to create a table called JoltData filled with rows of
data. You can examine the contents of your "database" file by looking
at file JoltData with a text editor. It will
look like this:
The ODBC-text driver will also create a file called schema.ini
containing metadata:
To retrieve information from a database, use SQL select
statements via the Java Statement.executeQuery method, which returns
results as rows of data in a ResultSet object. The results are
examined row-by-row using the ResultSet.next and
ResultSet.getXXX methods.
Consider how you would obtain the maximum number of cups of coffee
consumed by a programmer in one day. In terms of SQL, one way to get the
maximum value is to sort the table by the cups column in descending
order. The programmer column is selected, so the name attached
to the most coffee consumption can also be printed. Use the SQL statement:
From Java, execute the statement with:
The cups column of the first row of the result set will contain
the largest number of cups:
Examine the ResultSet by:
The information can be printed easily via:
Computing the total sales for the week is a matter of adding up the
cups column. Use an SQL select statement to retrieve the
cups column:
Peruse the results by calling method next until it returns
false, indicating that there are no more rows of data:
Print the total number of cups sold:
The output should be:
Here is the Java source for a complete
application to examine the JoltData table and generate the report.
will return a ResultSet with the same number of columns (and
rows) as the table, JoltData. If you do not know how many columns there
are beforehand, you must use metadata via the ResultSetMetaData class to
find out. Continuing the Cafe Jolt scenario, determine the number and
type of columns returned by the same SQL query
First, perform the usual execute method call:
Then obtain the column and type metadata from the ResultSet:
You can query the ResultSetMetaData easily to determine how many
columns there are:
and then walk the list of columns printing out their name and type:
Here is the Java source for a
complete application to print out some metadata associated with
the results of the query.
Currently, there are two choices for connecting your Java program to a data
source. First, you can obtain a JDBC driver from your database vendor that
acts as a bridge from JDBC to their database connection interface. Second,
JavaSoft provides a JDBC-ODBC bridge called class JdbcOdbcDriver and,
hence, you can connect to any ODBC data source.
Once you have established a JDBC database link, open a connection to that
data source through a Connection object obtained via
DriverManager.getConnection, which selects the appropriate driver
for talking with that source. All ODBC data sources are
identified via a URL in the form:
Given a connection, you can create statements, execute queries, and so on.
See the Getting Started
exercise for specific information about setting up ODBC data sources
on a PC.
Given a connection to a database, you can send SQL statements to
manipulate that database. Using the Connection.createStatement
method, obtain a Statement object and then execute method
executeQuery or executeUpdate. JDBC does not put
any restrictions on the SQL you send via the execute methods. but you must
ensure that the data source you are connecting to supports whatever SQL you
are using. To be JDBC-compliant, however, the data source must support at
least SQL-2 Entry Level capabilities.
Assuming the variable con contains a valid Connection object
obtained from the method DriverManager.getConnection, simple SQL update
statements (SQL INSERT, UPDATE or DELETE) can be sent to your database by
creating a Statement and then calling method executeUpdate.
For example, to create a table called Data with one row of data, use
the following:
The method executeUpdate returns the number of rows affected with 0
for SQL statements that return nothing.
In order to query a database (via the SQL SELECT statement), use the method
executeQuery, which returns a ResultSet object. The
ResultSet object returned is never null and contains the
rows of data selected by the SQL statement. For example, the following code
fragment selects two columns of data from our table called Data in
ascending height order:
The rows of resulting data are accessed in order, but the elements in the
various columns can be accessed in any order. However, for maximum portability
among databases, JavaSoft recommends that the columns be accessed in order from
left-to-right, and that each row be read only once. There is a "row cursor"
in the result that points at the current row. The method ResultSet.next
moves the cursor from row to row.
Before reading the first row, call method next
to initialize the cursor to the first row. The following code
fragment shows how to read the first two rows of data and print them out.
The method next returns false when another row is not available.
Note that column names are not case-sensitive,
and if more than one column
has the same name, the first one is accessed. Where possible, the column
index should be used. You can ask the ResultSet for the index of a
particular column if you do not know it beforehand.
Information about the properties of a ResultSet column is
provided by the class ResultSetMetaData and returned by the
ResultSet.getMetaData method.
See the section on MetaData for details.
PreparedStatement is an extension of Statement and,
consequently, behaves like a Statement except that you create them
with the method Connection.prepareStatement, instead of the method
Connection.createStatement:
Finally, execute the the prepared statement with the parameters set
most recently via the executeUpdate method:
There are many questions you can ask. For example, the following code
fragment asks the database for its product name and how many simultaneous
connections can be made to it.
All JDBC-compliant drivers support transactions. Check the
DatabaseMetaData associated with the appropriate connection to
determine the level of transaction-support a database provides.
A stored procedure is a block of SQL code stored in the database and executed
on the server. The
CallableStatement interface
allows you to interact with them. Working with CallableStatement objects
is very similar to working with PreparedStatements. The procedures have
parameters and can return either ResultSets or an update count.
Their parameters can be either input or output parameters. Input parameters are
set via the setXXX methods. Output parameters need to be registered
via the CallableStatement.registerOutParamter method. Stored procedures
need to be supported by the database in order to use them. You can ask the
DatabaseMetaData if it supports it via the method
supportsStoredProcedures. To demonstrate this interaction, return to Cafe Jolt. And, instead of a
weekly total, the manager asks for the daily total of a particular day of the week.
You can create a stored procedure to help, but this is
usually created by the database developer, not the applications programmer. Once
the procedure is created, the user does not need to know how it works
internally, just how to call it. Like any other SQL statement, you need a Connection and a
Statement to create the procedure:
For example, given a ResultSet containing rows of names and dates,
you can use getString and getDate to extract the information:
JDBC provides three types of exceptions: The SQLException
is the basis of all JDBC exceptions. It consists of
three pieces of information, a String message, like all
children of Exception, another String containing
the XOPEN SQL state (as described by specification), and a driver/source
specific int for an additional error code. In addition, multiple SQLException instances can be chained
together. The SQLWarning class
is similar to SQLException, however it is considered a noncritical
error and is not thrown. It is up to the programmer to poll for
SQLWarning messages through the getWarnings methods of
Connection, ResultSet, and Statement. If you
do not poll for them, you will never receive them. Also, the next time something is
done with a Connection, ResultSet, or Statement, the
previous warnings are cleared out. The DataTruncation class
is a special type of SQLWarning. It is reported with other SQLWarning
instances and indicates when information is lost during a read or write operation. To
detect a truncation, it is necessary to perform an instanceof DataTruncation
check on each SQLWarning from a getWarnings chain.
Although SQL is a standard, not all JDBC drivers support the full
ANSI92 grammar. Luckily, you can determine the level of conformance by asking.
The DatabaseMetaData
object contains three methods that report the grammar level supported by a driver. In addition to multiple ANSI92 support levels for JDBC drivers, there
are multiple SQL support levels for ODBC sources. You can determine the level of
these too by asking. The DatabaseMetaData object contains three methods
that report the grammar level supported by a database. These levels determine which specific SQL operations,
or which options of those operations, you can perform. Also, when using the JDBC-ODBC bridge, the ODBC driver can further
restrict your capabilities; for instance, you cannot use prepared statements
with the Text File ODBC Driver. Based upon the levels available, it may be beneficial to provide
alternative execution paths for certain operations. For instance, when
populating a table with values from another table, the core SQL grammar
permits a SELECT clause as part of the INSERT clause. This
would be much quicker than performing a select loop with an insert for each
record, which is necessary if you are relying on the minimum SQL grammar. |
Copyright © 1997 MageLang Institute. All Rights Reserved May-97 Copyright © 1996, 1997 Sun Microsystems Inc. All Rights Reserved |