Java 2 - The Complete Reference
Java 2 - The Complete Reference
Sea rc h th is bo ok:
Go!
Introduction
1
Chapter 4The InteractiveSQL Applet
Your First JDBC Applet
The Blueprint
Getting A Handle On The JDBC Essentials: The
Complete Applet Source Code
The Look Of The Applet
Handling Events
Opening The Connection
No Guts, No Glory: Executing Queries And
Processing Results
Wrapping It Up
The HTML File That Calls The Applet
The Final Product
Coming Up Next
2
Creating The Menu
Creating The Lists
Handling Events
Saving The Image
Summary
3
Checking For Tracing
Data Coercion
Escape Clauses
Date, Time, And Timestamp
Scalar Functions
LIKE Predicate Escape Characters
Outer Joins
Procedures
The JDBC Interfaces
Driver
Connection
DatabaseMetaData
Statement
PreparedStatement
ResultSet
ResultSetMetaData
Summary
4
public interface ResultSet
public interface ResultSetMetaData
public interface Statement
Exceptions
public class DataTruncation
public class SQLException
public class SQLWarning
Appendix A
Appendix B
Appendix C
Appendix D
Index
Chapter 1
JDBC: Databases The Java Way!
The Internet has spurred the invention of several new technologies in client/server
computingthe most recent of which is Java. Java is two-dimensional: Its a
programming language and also a client/server system in which programs are
automatically downloaded and run on the local machine (instead of the server machine).
The wide embrace of Java has prompted its quick development. Java includes Java
compilers, interpreters, tools, libraries, and integrated development environments (IDEs).
Javasoft is leading the way in the development of libraries to extend the functionality and
usability of Java as a serious platform for creating applications. One of these libraries,
called Application Programming Interfaces (APIs), is the Java Database Connectivity
API, or JDBC. Its primary purpose is to intimately tie connectivity to databases with the
Java language.
Well discuss the reasoning behind the JDBC in this chapter, as well as the design of the
JDBC and its associated API. The Internet, or better yet, the technologies used in the
operation of the Internet, are tied into the design of the JDBC. The other dominant design
basis for the JDBC is the database standard known as SQL. Hence, the JDBC is a fusion
of three discrete computer areas: Java, Internet technology, and SQL. With the growing
implementation of these Internet technologies in closed networks, called intranets, the
time was right for the development of Java-based enterprise APIs. In this book, intranet
and Internet are both used to describe the software technology behind the network, such
as the World Wide Web.
5
Its an API for creating the low-level JDBC drivers,
which do the actual connecting/transacting with data
sources.
Its based on the X/Open SQL Call Level Interface
(CLI) that defines how client/server interactions are
implemented for database systems.
Confused yet? Its really quite simple: The JDBC defines every aspect of making data-
aware Java applications and applets. The low-level JDBC drivers perform the database-
specific translation to the high-level JDBC interface. This interface is used by the
developer so he doesnt need to worry about the database-specific syntax when
connecting to and querying different databases. The JDBC is a package, much like other
Java packages such as java.awt. Its not currently a part of the standard Java Developers
Kit (JDK) distribution, but it is slated to be included as a standard part of the general Java
API as the java.sql package. Soon after its official incorporation into the JDK and Java
API, it will also become a standard package in Java-enabled Web browsers, though there
is no definite timeframe for this inclusion. The exciting aspect of the JDBC is that the
drivers necessary for connection to their respective databases do not require any pre-
installation on the clients: A JDBC driver can be downloaded along with an applet!
The JDBC project was started in January of 1996, and the specification was frozen in
June of 1996. Javasoft sought the input of industry database vendors so that the JDBC
would be as widely accepted as possible when it was ready for release. And, as you can
see from this list of vendors who have already endorsed the JDBC, its sure to be widely
accepted by the software industry:
Borland International, Inc.
Bulletproof
Cyber SQL Corporation
DataRamp
Dharma Systems, Inc.
Gupta Corporation
IBMs Database 2 (DB2)
Imaginary (mSQL)
Informix Software, Inc.
Intersoft
Intersolv
Object Design, Inc.
Open Horizon
OpenLink Software
Oracle Corporation
Persistence Software
Presence Information Design
PRO-C, Inc.
Recital Corporation
RogueWave Software, Inc.
6
SAS Institute, Inc.
SCO
Sybase, Inc.
Symantec
Thunderstone
Visigenic Software, Inc.
WebLogic, Inc.
XDB Systems, Inc.
The JDBC is heavily based on the ANSI SQL-92 standard, which specifies that a JDBC
driver should be SQL-92 entry-level compliant to be considered a 100 percent JDBC-
compliant driver. This is not to say that a JDBC driver has to be written for an SQL-92
database; a JDBC driver can be written for a legacy database system and still function
perfectly. As a matter of fact, the simple JDBC driver included with this book uses
delimited text files to store table data. Even though the driver does not implement every
single SQL-92 function, it is still a JDBC driver. This flexibility will be a major selling
point for developers who are bound to legacy database systems but who still want to
extend their client applications.
7
the Java program if a different type of database is used (assuming that the JDBC driver
for the other database is available). This is especially useful in the scenario of distributed
databases.
8
Figure 1.2 ODBC in the JDBC model.
ODBC drivers function in the same manner as true JDBC drivers; in fact, the JDBC-
ODBC bridge is actually a sophisticated JDBC driver that does low-level translation to
and from ODBC. When the JDBC driver for a certain database becomes available, you
can easily switch from the ODBC driver to the new JDBC driver with few, if any,
changes to the code of the Java program.
Summary
The JDBC is not only a specification for using data sources in Java applets and
applications, but it also allows you to create and use low-level drivers to connect and
talk with data sources. You have now explored the JDBC architecture and seen how the
ODBC fits into the picture. The important concept to remember about the JDBC is that
the modular design of the JDBC interface allows you to change between drivershence
databaseswithout recoding your Java programs.
In the next chapter, well take a step back to give you a quick primer on SQL, one of the
pillars of the JDBC. If you are already familiar with SQL-92, feel free to skip the chapter.
However, I think that you may find the chapter helpful in clarifying the SQL queries
performed in the sample JDBC programs we develop in this book.
Chapter 2
SQL 101
SQLthe language of database. This chapters primary purpose is to serve as a primer
on this data sublanguage. Although it would be impossible for me to cover the intricacies
of SQL in just one chapter, I do intend to give you a solid introduction that well build on
in the remainder of this book. Because the JDBC requires that drivers support the ANSI
SQL-92 standard to be JDBC compliant, Ill be basing this chapter on that standard.
SQL-92, which Ill refer to as SQL, is based on the relational model of database
management proposed in 1970 by Dr. E.F. Codd; over time, SQL evolved into the full-
featured language it is today, and it continues to evolve with our ever-changing needs.
9
A JDBC driver doesnt absolutely have to be SQL-92 compliant. The JDBC specification
states the following: In order to pass JDBC compliance tests and to be called JDBC
compliant, we require that a driver support at least ANSI SQL-92 Entry Level. This
requirement is clearly not possible with drivers for legacy database management systems
(DBMS). The driver in these cases will not implement all of the functions of a
compliant driver. In Chapter 10, Writing JDBC Drivers, we develop the basics of a
JDBC driver that implements only some of the features of SQL, but is a JDBC driver
nonetheless.
Well start our exploration of SQL by discussing the relational model, the basis for SQL.
Then well cover the essentials of building data tables using SQL. Finally, well go into
the manipulation and extraction of the data from a datasource.
10
A word of caution: While the keywords are not case sensitive, the string values that are
stored as data in a table do preserve case, as you would expect. Keep this in mind when
doing string comparisons in queries.
Putting It Into Perspective: Schema And Catalog
Though you can stick all of your data into a single table, it doesnt make sense logically
to do this all the time. For example, in our EMPLOYEE table shown previously, we
could add information about company departments; however, the purpose of the
EMPLOYEE table is to store data on the employees. The solution is for us to create
another table, called DEPARTMENT, which will contain information about the specific
departments in the company. To associate an employee with a department, we can simply
add a column to the EMPLOYEE table that contains the department name or number.
Now that we have employees and departments neatly contained, we can add another table,
called PROJECT, to keep track of the projects each employee is involved in. Figure 2.2
shows our tables.
Figure 2.2 The EMPLOYEE, DEPARTMENT, and PROJECT tables track employees
by department and project.
Now that you understand how to logically separate your data, its time to take our model
one step higher and introduce you to the schema/catalog relationship. The schema is a
higher-level container that is defined as a collection of zero or more tables, where a table
belongs to exactly one schema. In the same way, a catalog can contain zero or more
schemas. This abstract is a necessary part of a robust relational database management
system (RDBMS). The primary reason is access control: It facilitates who can read a
table, who can change a table, and even who can create or destroy tables. Figure 2.3
demonstrates this point nicely. Here we have added another table, called
CONFIDENTIAL. It contains the home address, home phone number, and salary of each
employee. This information needs to belong in a separate schema so that anyone who is
not in payroll cannot access the data, while allowing those in marketing to get the
necessary data to do their job.
Figure 2.3 The table, schema, and catalog relationship allows you to limit access to
confidential information.
11
Introducing Keys
As you can see in the previous example, we have purposely set up the three tables to link
to one another. The EMPLOYEE table contains a column that has the department number
that the employee belongs in. This department number also appears in the
DEPARTMENT table, which describes each department in the company. The
EMPLOYEE and CONFIDENTIAL tables are related, but we still need to add one
corresponding entry (row) in one table for each entry in the other, the distinction coming
from the employees number.
The linkemployee number and department numberwe have set up can be thought of
as a key. A key is used to identify information within a table. Each individual employee
or department should have a unique key to aid in various functions performed on the
tables. In keeping with the relational model, the key is supposed to be unique within the
table: No other entry in the table may have the same primary key.
A single column is sometimes enough to uniquely identify a row, or entry. However, a
combination of rows can be used to compose a primary keyfor example, we might
want to just use the combination of the title and city location of a department to comprise
the primary key. In SQL, columns defined as primary keys must be defined. They cannot
be undefined (also known as NULL).
Using Multiple Tables And Foreign Keys
As we have shown, its best to split data into tables so that the data contained within a
table is logically associated. Oftentimes, the data will belong logically in more than one
table, as is the case of the employee number in the EMPLOYEE and CONFIDENTIAL
tables. We can further define that if a row in one table exists, a corresponding row must
exist in another table; that is, we can say that if there is an entry in the EMPLOYEE table,
there must be a corresponding entry in the CONFIDENTIAL table. We can solidify this
association with the use of foreign keys, where a specific column in the dependent table
matches a column in a parent table. In essence, we are linking a virtual column in
one table to a real column in another table. In our example database, we link the
CONFIDENTIAL tables employee number column to the employee number column in
the EMPLOYEE table. We are also specifying that the employee number is a key in the
CONFIDENTIAL table (hence the term foreign key). A composite primary key can
contain a foreign key if necessary.
We can create a logical structure to our data using the concept of a foreign key. However,
in preparation, youll have to put quite a bit of thought into creating your set of tables; an
efficient and planned structure to the data by way of the tables and keys requires good
knowledge of the data that is to be modeled. Unfortunately, a full discussion on the
techniques of the subject is beyond the scope of this book. There are several different
ways to efficiently model data; Figure 2.4 shows one visualization of the database we
have created. The SQL queries we perform in the examples of this book are not very
complex, so the information outlined in this section should suffice to convey a basic
understanding of the example databases created throughout the following chapters.
12
Figure 2.4 E-R diagram of relationships between tables.
Performing Checks
Predefining a data object is also useful for making sure that a certain entry in a column
matches the data we expect to find there. For example, our empno field should contain a
number. If it doesnt, performing a check of that data will alert us to the error. These
checks can exist in the actual table definition, but its efficient to localize a check in a
domain. Hence, we can add a check to our employee number domain:
CREATE DOMAIN EMP_NUMBER AS CHAR(5) CHECK (VALUE IS NOT NULL);
13
Now our domain automatically checks for any null entries in columns defined as
EMP_NUMBER. This statement avoids problems that crop up from non-existent entries,
as well as allowing us to catch any rogue SQL queries that add an incorrect (those that do
not set the employee number) entry to the table.
Creating Tables
Creating a table in SQL is really pretty easy. The one thing you need to keep in mind is
that you should define the referenced table, in this case EMPLOYEE, before defining the
referencing table, CONFIDENTIAL. The following code creates the EMPLOYEE table
shown in Figure 2.2:
CREATE TABLE EMPLOYEE
(
empno CHAR(5) PRIMARY KEY,
lastname VARCHAR(20) NOT NULL,
firstname VARCHAR(20) NOT NULL,
function VARCHAR(20) NOT NULL,
department VARCHAR(20)
);
We also could have easily incorporated the domain that we defined earlier into the
creation of the table, as shown here:
CREATE DOMAIN EMP_NUMBER AS CHAR(5) CHECK (VALUE IS NOT NULL);
14
homeaddress VARCHAR(50),
homephone VARCHAR(12),
salary DECIMAL,
FOREIGN KEY ( empno ) REFERENCES EMPLOYEE ( empno )
)
We have tied the empno field in the CONFIDENTIAL table to the empno field in the
EMPLOYEE table. The fact that we used the same name, empno, is a matter of choice
rather than a matter of syntax. We could have named the empno field whatever we
wanted in the CONFIDENTIAL table, but we would need to change the first field
referred to in the FOREIGN KEY declaration accordingly.
Manipulating Tables
Database management often requires you to make minor modifications to tables.
However, careful planning can help you keep these alterations to a minimum. Lets begin
by dropping, or removing, a table from a database:
DROP TABLE EMPLOYEE;
This is all we have to do to remove the EMPLOYEE table from our database. However,
if the table is referenced by another table, as is the case with the CONFIDENTIAL table,
a RDBMS may not allow this operation to occur. In this situation, you would have to
drop any referencing tables first, and then rebuild them without the referencing.
Altering a table definition is as straightforward as dropping a table. To remove a column
from a table, issue a command like this:
ALTER TABLE EMPLOYEE
DROP firstname;
Of course, if this column is part of the tables key, you wont be able to remove it. Also,
if the column is referenced by another table, or there is another column in any table that is
dependent on this column, the operation is not allowed.
To add a column to a table, run a query like this:
ALTER TABLE CONFIDENTIAL
ADD dateofbirth DATE NOT NULL;
You can also make multiple alterations at one time with the ALTER clause.
15
'Author',
''
);
Here we have inserted the appropriate information in the correct order into the
EMPLOYEE table. To be safe, you can specify which field each of the listed tokens goes
into:
INSERT INTO EMPLOYEE (empno, lastname, firstname, function, department)
VALUES (
'00201', 'Pratik', 'Patel', 'Author', ''
);
If you dont want to add all the fields in the row, you can specify only the fields you wish
to add:
INSERT INTO EMPLOYEE (empno, lastname, firstname, function)
VALUES (
'00201', 'Pratik', 'Patel', 'Author'
);
As you can see, I chose not to add anything in the department field. Note that if a fields
check constraint is not met, or a table check is not met, an error will be produced. For
example, if we did not add something under the firstname field, an error would have been
returned because we defined the tables firstname column check as NOT NULL. We did
not set up a check for the department field, so the previous command would not produce
an error.
To delete a tables contents without removing the table completely, you can run a
command like this:
DELETE FROM EMPLOYEE;
This statement will wipe the table clean, leaving no data in any of the columns, and,
essentially, deleting all of the rows in the table. Deleting a single entry requires that you
specify some criteria for deletion:
DELETE FROM EMPLOYEE
WHERE empno='00201';
You can delete multiple rows with this type of operation, as well. If the WHERE clause
matches more than one row, all of the rows will be deleted. You can also delete multiple
entries by using the SELECT command in the WHERE clause; we will get to the
SELECT command in the next section.
If you really want to get fancy, you can use one statement to delete the same row from
more than one table:
DELETE FROM EMPLOYEE, CONFIDENTIAL
WHERE empno='00201';
The final command I want to cover in this section is UPDATE. This command allows
you to change one or more existing fields in a row. Here is a simple example of how to
change the firstname field in the EMPLOYEE table:
UPDATE EMPLOYEE
SET firstname = 'PR'
WHERE empno='00201';
16
We can set more than one field, if we wish, by adding more expressions, separated by
commas, like this:
UPDATE EMPLOYEE
SET firstname='PR', function='Writer'
WHERE empno='00201';
As youll see in the next section, the WHERE clause can take the form of a SELECT
query so that you can change multiple rows according to certain criteria.
Mastering SQL querying is not an easy task, but with the proper mind set, it is intuitive
and efficient, thanks to the relational model upon which SQL is based.
The syntax of the SELECT statement is shown here:
SELECT column_names
FROM table_names
WHERE predicates
Lets take a look at the various functions of the SELECT command. To retrieve a
complete table, run this query:
SELECT * FROM EMPLOYEE;
To get a list of employees in the Editorial department, run this query:
SELECT * FROM EMPLOYEE
WHERE department = 'Editorial';
To sort the list based on the employees last names, use the ORDER BY directive:
SELECT * FROM EMPLOYEE
WHERE department= 'Editorial'
ORDER BY lastname;
To get this ordered list but only see the employee number, enter the following statements:
SELECT empno FROM EMPLOYEE
17
WHERE department = 'Editorial'
ORDER BY lastname;
To get a list of users with the name Pratik Patel, you would enter:
SELECT * FROM EMPLOYEE
WHERE (firstname='Pratik') AND (lastname='Patel');
What if we want to show two tables at once? No problem, as shown here:
SELECT EMPLOYEE.*, CONFIDENTIAL.*
FROM EMPLOYEE, CONFIDENTIAL;
Heres a more challenging query: Show the salary for employees in the Editorial
department. According to our tables, the salary information is in the CONFIDENTIAL
table, and the department in which an employee belongs is in the EMPLOYEE table.
How do we associate a comparison in one table to another? Since we used the reference
of the employee number in the CONFIDENTIAL table from the EMPLOYEE table, we
can specify the employees that match a specified department, and then use the resulting
employee number to retrieve the salary information from the CONFIDENTIAL table:
SELECT c.salary
FROM EMPLOYEE as e, CONFIDENTIAL as c
WHERE e.department = 'Editorial'
AND c.empno = e.empno;
We have declared something like a variable using the as keyword. We can now reference
the specific fields in the table using a ., just like an object. Lets begin by determining
which people in the entire company are making more than $25,000:
SELECT salary
FROM CONFIDENTIAL
WHERE salary > 25000;
Now lets see who in the Editorial department is making more than $25,000:
SELECT c.salary
FROM EMPLOYEE as e, CONFIDENTIAL as c
WHERE e.department = 'Editorial'
AND c.empno = e.empno
AND c.salary > 25000;
You can perform a number of other functions in SQL, including averages. Heres how to
get the average salary of the people in the Editorial department:
SELECT AVG (c.salary)
FROM EMPLOYEE as e, CONFIDENTIAL as c
WHERE e.department = 'Editorial'
AND c.empno = e.empno;
Of course, the possibilities with SQL exceed the relatively few examples shown in this
chapter. Because this books goal is to introduce the JDBC specifically, I didnt use
complex queries in the examples. And now our discussion on SQL is complete. If you are
interested in learning more about SQL, I recommend that you check out our books
Website, where I have posted a list of recommended books on the topic of SQL and
distributed databases.
Coming Up Next
18
The next chapter begins our journey into JDBC. Ill show you how to use JDBC drivers
for connecting to data sources. Then well cover installing drivers, as well as the proper
way to use drivers that are dynamically fetched with an applet. Finally, well discuss the
security restrictions of using directly downloaded drivers as opposed to locally installed
drivers.
Chapter 3
Using JDBC Drivers
As a developer whos using the JDBC, one of the first things you need to understand is
how to use JDBC drivers and the JDBC API to connect to a data source. This chapter
outlines the steps necessary for you to begin that process. Well be covering the details of
getting JDBC drivers to work, as well as the driver registration process we touched on in
Chapter 1. Well also take some time to explore JavaSofts JDBC-ODBC Bridge, which
allows your Java programs to use ODBC drivers to call ODBC data sources.
Before our discussion gets underway though, I need to point out a few things about JDBC
drivers. First, there are no drivers packaged with the JDBC API; you must get them
yourself from software vendors. Check out this books Web site for links to demo
versions of drivers for your favorite database server, as well as free JDBC drivers
available on the Internet. Second, if you want to use ODBC, dont forget that youll need
ODBC drivers, as well. If you dont have a database server, but you want to use JDBC,
dont despair: You can use the ODBC drivers packaged with Microsoft Access. Using the
JDBC-ODBC Bridge, you can write Java applications that can interact with an Access
database.
Unfortunately, applets enforce a security restriction that does not allow access to the local
disk, so ODBC drivers might not work in the applet context (inside a Web browser). A
future release of the Java Development Kit (JDK) may change or relax this security
restriction. A workaround for Java-enabled Web browsers is being prepared, and by the
time you read this, it may very well be possible to use the JDBC-ODBC bridge. Using
ODBC drivers in Java programs also requires pre-installation of the ODBC drivers and
JDBC-ODBC Bridge on the client machine. In contrast, JDBC drivers that are 100
percent Java class files can be downloaded dynamically over the network, along with the
calling applets class file. Ill provide a more thorough discussion of this point in Chapter
9.
19
Figure 3.1 The JDBC classes to call.
The following (Listing 3.1) is a very simple JDBC application that follows these four
steps. It runs a query and gets one row from the returned result. If you dont understand
everything going on here, dont worryits all explained in detail in Chapter 4.
Listing 3.1 Example JDBC application.
import java.net.URL;
import java.sql.*;
class Select {
public static void main(String argv[]) {
try {
new imaginary.sql.iMsqlDriver();
String url = "jdbc:msql://elanor.oit.unc.edu:1112/bcancer";
Connection con = DriverManager.getConnection(url, "prpatel",
"");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Users");
System.out.println("Got results:");
while(rs.next()) {
}
stmt.close();
con.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
Installing java.sql.*
The java.sql.* package contains the JDBC base API classes, which are supposed to be
20
Installing java.sql.*
The java.sql.* package contains the JDBC base API classes, which are supposed to be in
the normal java.* hierachy that is distributed as part of the Java API (which includes the
java.awt, java.io, and java.lang packages). Currently, the JDBC API is not distributed
with the JDK, but it is slated to be included in the next release. I have a sneaking
suspicion that the java.sql.* package will also be included in the future APIs of popular
Java-enabled Web browsers.
However, you dont have to wait for this updated software to be released. You can grab
the JDBC API classes from the accompanying CD-ROM or from the JavaSoft Web site at
http://splash.java.com/jdbc. As I was writing this chapter, the classes were stored in a file
named jdbc.100.tar.Z. By the time you read this chapter, however, the file name may
be slightly different. Once you have your software, simply follow these easy instructions
to install the API classes in the proper place on your computers hard disk. The method
shown here allows you to compile and run Java applications and applets (using the
Appletviewer) that use the JDBC:
1. Download the JDBC API package from the JavaSoft
Web site or make a copy of the file from the CD-ROM.
2. On your hard drive, locate the directory that stores
the Java API packages. (On my PC, the directory is
C:\JAVA\SRC, and on my Sun box, the directory is
\usr\local\java\src.) You do not need to install the
JDBC API package in the same directory as the rest of
the Java API, but I strongly recommend that you do
because, as I mentioned earlier, the JDBC API will soon
be a standard part of the Java API distribution and will
be packaged in the Java API hierarchy.
3. Unpack the JDBC API classes using one of the
following methods (for Unix-based machines or PCs),
substituting the location where you downloaded the
JDBC class file and the location where you want to
install the JDBC classes.
Unix Procedure:
To upack the file, enter prompt> uncompress
\home\prpatel\jdbc.100.tar.Z.
To create a jdbc directory with the classes and their
source in separate directories, enter prompt> tar xvf
\home\prpatel\jdbc.100.tar.Z.
To install the JDBC classes, enter prompt> cd
\usr\local\java\src, then enter prompt> mv
\home\prpatel\jdbc\classes\java, and finally enter
prompt> mv \home\prpatel\jdbc\src\java.
21
Windows 95 Procedure:
Using a Windows 95 ZIP utility such as WinZip,
uncompress and untar the file. Be sure the file name
ends with .tar when you uncompress the file so that
utilities will recognize the file. Untar the file to a
tempory folder. Then do the following:
Copy the java folder from the JDBC\CLASSES
directory (from the temp directory where you untarred
the downloaded file) to the C:\JAVA\SRC directory.
Copy the java folder from the JDBC\SRC directory to
C:\JAVA\SRC.
4. Set the CLASSPATH to point to c:/usr/local/java/src
(for Unix-based machines) or C:\JAVA\SRC (for PCs).
Again, remember to substitute your location if this is
not where you installed the downloaded file.
I must stress that you should make sure that you have the CLASSPATH set properly. The
package will be called in the following way in your Java program:
import java.sql.*
You need to point the CLASSPATH at the parent of the java directory you copied in Step
2, which is why we set the CLASSPATH in Step 3. The package is contained in the
java/sql/ folder, which is exactly as it should be according to the calling code snippet
above.
22
When you want to identify a list of drivers that can be loaded with the DriverManager,
you can set the sql.drivers system property. Because this is a system property, it can be
set at the command line using the -D option:
java -Dsql.drivers=imaginary.sql.iMsqlDriver classname
If there is more than one driver to include, just separate them using colons. If you do
include more than one driver in this list, the DriverManager will look at each driver
once the connection is created and decide which one matches the JDBC URL supplied in
the Connection class instantiation. (Ill provide more detail on the JDBC URL and the
Connection class later on.) The first driver specified in the URL that is a successful
candidate for establishing the connection will be used.
Theres Always A Class For A Name
You can explicitly load a driver using the standard Class.forName method. This
technique is a more direct way of instantiating the driver class that you want to use in the
Java program. To load the mSQL JDBC driver, insert this line into your code:
Class.forName("imaginary.sql.iMsqlDriver");
This method first tries to load the imaginary/sql/iMsqlDriver from the local
CLASSPATH. It then tries to load the driver using the same class loader as the Java
programthe applet class loader, which is stored on the network.
Just Do It
Another approach is what I call the quick and dirty way of loading a JDBC driver. In
this case, you simply instantiate the drivers class. Of course, I dont advise you to take
this route because the driver may not properly register with the JDBC DriverManager.
The code for this technique, however, is quite simple and worth mentioning:
new imaginary.sql.iMsqlDriver;
Again, if this is in the applet context, this code will first try to find this driver in the local
CLASSPATH, then it will try to load it from the network.
23
port number or catalog. Again, this is dependent on the subprotocols JDBC driver.
JavaSoft suggests that a network name follow the URL syntax:
jdbc:<subprotocol>://hostname:port/subsubname
The mSQL JDBC driver used in this book follows this syntax. Heres the URL you will
see in some of the example code:
jdbc:msql://mycomputer.com:1112/databasename
The DriverManager.getConnection method in the JDBC API uses this URL when
attempting to start a connection. Remember that a valid driver must be registered with the
JDBC DriverManager before attempting to create this connection (as I discussed earlier
in the Registering and Calling JDBC Drivers section). The
DriverManager.getConnection method can be passed in a Property object where the
keys user, password, and even server are set accordingly. The direct way of using
the getConnection method involves passing these attributes in the constructor. The
following is an example of how to create a Connection object from the
DriverManager.getConnection method. This method returns a Connection object
which is to be assigned to an instantiated Connection class:
String url="jdbc:msql://mydatabaseserver.com:1112/databasename";
Name = "pratik";
password = "";
Connection con;
con = DriverManager.getConnection(url, Name, password);
// remember to register the driver before doing this!
Chapter 4 shows a complete example of how to use the DriverManager and Connection
classes, as well as how to execute queries against the database server and get the results.
24
2. Move the jdbc directory (located in the jdbc-
odbc/classes directory) into a directory listed in your
CLASSPATH, or move it to your regular Java API tree.
3. Move JdbcOdbc.dll into your java/bin directory to
make sure that the system and Java executables can
find the file. You can also:
For Unix:
Add the path location of the JdbcOdbc.dll to your
LD_LIBRARY_PATH, or move the DLL into a directory
covered by this environment variable.
25
That is all you need to do to set up the ODBC data source. Now you can write Java
applications to interact with the data source on the machine in which you performed the
configuration; the ODBC driver is not directly accessible over the network. You can
access the data source by using the name you supplied in Step 5. For example, the URL
would be something like
jdbc:odbc:DataSourceName
and the statement
Class.forName("jdbc.odbc.JdbcOdbcDriver")
would load the JDBC-ODBC bridge.
Summary
The next chapter works through a complete example of using a JDBC driver. I use the
mSQL driver to query an mSQL database server over the network. The JDBC driver can
easily be changed to use an ODBC driver or another JDBC driver to connect to a
different data source.
Chapter 4
The Interactive
SQL Applet
Now that you have seen how to use JDBC drivers, its time we ante up. In this chapter,
we jump into the JDBC with an example applet that well build on and derive from
through the rest of the book. Our Interactive Query applet will accomplish a number of
tasks. It will:
Connect to a database server, using a JDBC driver
Wait for a user to enter an SQL query for the
database server to process
Display the results of the query in another text area
Of course, before we can get to the programming details of the applet, we need to take a
step back, review the basics, and put together a plan. I know, plans take time to develop,
and you want to get into the good stuff right away. But trust me, well be saving
ourselves a lot of trouble later on by figuring out just the right way to get to where we
want to go.
26
are unsure about what an applet really is, and why its different from a generic
application, you will want to read this section all the way through.
The Blueprint
The applet structure has a well-defined flow, and is an event-driven development. Lets
begin by defining what we want the SQL query applet to do at a high level. First, we
want to connect to a database, which requires some user input: the database we want to
connect to, a user name, and, possibly, a password. Next, we want to let the user enter an
SQL query, which will then be executed on the connected data source. Finally, we need
to retrieve and display the results of the query. Well make this applet as simple as
possible (for now), so that you understand the details of using the JDBC API and have a
firm grasp of the foundations of making database-aware Java applets.
Our next task is to fill in some of the technical details of our plan. The absolute first thing
we need to do, besides setting up the constructors for the various objects we use, is design
and layout the user interface. We arent quite to that phase yet (remember, were still in
the planning phase), so well defer the design details for a later section of this chapter,
The Look of the Applet.
We need to get some preliminary input from the user; we need to have some event
handlers to signal the applet that the user has entered some information that needs to be
processed, like the SQL query. Finally, we need to clean up when the applet is terminated,
like closing the connection to the data source.
Figure 4.1 shows the flow diagram for the applet. As you can see, we do most of our real
work in the Select method. The dispatcher is the event handler method, handleEvent().
We use several global objects so that we dont have to pass around globally used objects
(and the data contained within). This approach also adds to the overall efficiency; the
code shows how to deal with some of the events directly in the event handler.
27
Java environment, designed to control the applets behavior. Note that Java applications
do not follow this life-cycle, as they are not bound to run in the context of Java applets.
Heres a synopsis of what the four overridable methods, or steps, do in the context of
Java applets:
28
The flow chart in Figure 4.1 shows some of the events we want to process. In this applet,
we are only looking for keystrokes and mouse clicks. We override the handleEvent
method to allow us to program for these events. We use the target property of the Event
object, which is passed into the event handler, to look for a specific object. Then we can
look for more specific events. Listing 4.1 contains a snippet of code that shows how we
deal with the user entering a name in the TextArea NameField.
Listing 4.1 Trapping for the Enter key event in a specific object.
if (evt.target == NameField)
{char c=(char)evt.key;
if (c == '\n')
{ Name=NameField.getText();
return true;
}
else { return false; }
}
The object evt is the local instantiation of the Event parameter that is part of the
handleEvent method, as well see later in the complete source code listing. We use the
target property to see which object the event occurred in, then we look at the key
property to see if the Enter key was pressed. The Java escape sequence for Enter is \n.
The rest of the code shown in the listing is fairly straightforward: We compare the
pressed key to the enter escape sequence, and if we come up with a match, we set the
Name string variable to the text in the NameField using the TextArea getText method.
Because we have processed the event, and we want to let the rest of the event handler
know that weve dealt with it, we return true. If this wasnt the key we were looking for
in this specific object (NameField), we would return false so that the other event handling
code could attempt to process this event.
Finishing Up
One of Javas great strengths lies in its ability to automatically allocate and de-allocate
memory for objects created in the program, so the programmer doesnt have to. We
primarily use the destroy method to close the database connection that we open in the
applet. The JDBC driver that we used to connect to the data source is alerted to the fact
that the program is exiting, so it can gracefully close the connection and flush input and
output buffers.
29
the applet. See Chapter 3 if you have trouble getting the applet to run and you keep
getting the Cant Find a Driver or Class not found error.
import java.sql.*;
// These are the packages needed to load the JDBC kernel, known as the
// DriverManager.
import imaginary.sql.*;
// These are the actual driver classes! We are using the msql JDBC
// drivers to access our msql database.
30
GridBagLayout, a Java layout manager, to position the components in the applet
window. GridBagLayout is flexible and offers us a quick way of producing an attractive
interface.
Listing 4.3 Setting up the user interface.
public void init() {
QueryField.setEditable(true);
OutputField.setEditable(false);
NameField.setEditable(true);
DBurl.setEditable(true);
// We want to set the individual TextArea and TextField to be editable
so
// the user can edit the OutputField, where we plan on showing the
// results of the query.
setLayout(gridbag);
// Set the layout of the applet to the gridbag that we created above.
setFont(new Font("Helvetica", Font.PLAIN, 12));
setBackground(Color.gray);
// Set the font and color of the applet.
Con.weightx=1.0;
Con.weighty=0.0;
Con.anchor = GridBagConstraints.CENTER;
Con.fill = GridBagConstraints.NONE;
Con.gridwidth = GridBagConstraints.REMAINDER;
This code requires some explanation. The weightx and weighty properties determine
how the space in the respective direction is distributed. If either weight property is set to
0, the default, any extra space is distributed around the outside of the components in the
corresponding direction. The components are also centered automatically in that direction.
If either weight property is set to 1, any extra space is distributed within the spaces
between components in the corresponding direction. Hence, in setting the weightx=1, we
have told the GridBagLayout layout manager to position the components on each row so
that extra space is added equally between the components on that row. However, the rows
of components are vertically clumped together because the weighty property is set to
0.0. Later on, well change weighty to 1 so that the large TextArea (the OutputField)
takes up extra space equal to all the components added before it. Take a look at Figure
4.3, shown at the end of the chapter, to see what I mean.
We also set the anchor property to tell the GridBagLayout to position the components
on the center, relative to each other. The fill property is set to NONE so that the
components are not stretched to fill empty space. You will find this technique to be useful
when you want a large graphics area (Canvas) to take up any empty space that is
available around it, respective to the other components. The gridwidth is set to
31
REMAINDER to signal that any component assigned the GridBagContstraint Con
takes up the rest of the space on a row. Similarly, we can set gridheight to
REMAINDER so that a component assigned this constraint takes up the remaining
vertical space. The last detail associated with GridBagLayout involves assigning the
properties to the component. This is done via the setConstraints method in
GridBagLayout.
Listing 4.4 shows how we do this. Notice that we assign properties for the TextArea, but
not for the Labels. Because were positioning the Labels on the right side of the screen
(the default), there is no need to assign constraints. There are more properties you can set
with GridBagLayout, but its beyond the scope of this book.
Listing 4.4 Assigning properties to components.
add(new Label("Name"));
gridbag.setConstraints(NameField, Con);
add(NameField);
// Note that we did not setConstraints for the Label. The GridbagLayout
// manager assumes they carry the default constraints. The NameField is
// assigned to be the last component on its row via the constraints Con,
// then added to the user interface.
gridbag.setConstraints(ConnectBtn, Con);
add(ConnectBtn);
// Here, we only want the ConnectBtn button on a row, by itself, so we
// set the constraints, and add it.
Con.weighty=1.0;
gridbag.setConstraints(OutputField, Con);
OutputField.setForeground(Color.white);
OutputField.setBackground(Color.black);
add(OutputField);
// This is what we were talking about before. We want the large
OutputField to
// take up as much of the remaining space as possible, so we set the
// weighty=1 at this point. This sets the field apart from the
previously
// added components, and gives it more room to exist in.
show();
32
} //init
Everything has been added to the user interface, so lets show it! We also dont need to
do anything else as far as preparation, so that ends the init method of our applet. Now we
can move on to handling events.
Handling Events
We want to watch for four events when our applet is running: the user pressing the Enter
key in the DBurl, NameField, and QueryField TextAreas, and the user clicking on the
Connect button. Earlier in the chapter, we saw how to watch for events, but now we get
to see what we do once the event is trapped, as shown in Listing 4.5. The event handling
code is contained in the generic handleEvent method.
Listing 4.5 Handling events.
public boolean handleEvent(Event evt) {
// The standard format for this method includes the Event class where
// all the properties are set.
if (evt.target == NameField)
{char c=(char)evt.key;
// Look for the Enter key pressed in the NameField.
if (c == '\n')
{ Name=NameField.getText();
// Set the global Name variable to the contents in the NameField.
return true;
}
else { return false; }
}
if (evt.target == DBurl)
{char c=(char)evt.key;
// Look for the enter key pressed in the DBurl TextArea.
if (c == '\n')
{ url=DBurl.getText();
// Set the global url variable to the contents of the DBurl TextArea.
return true;
}
else { return false; }
}
if (evt.target == QueryField)
{char c=(char)evt.key;
// Look for the Enter key pressed in the QueryField.
if (c == '\n')
{
OutputField.setText(Select(QueryField.getText()));
// Get the contents of the QueryField, and pass them to the Select
// method that is defined in Listing 4.7. The Select method executes the
// entered query, and returns the results. These results are shown in
the
// OutputField using the setText method.
return true;
}
else { return false; }
33
}
url=DBurl.getText();
Name=NameField.getText();
try {
new imaginary.sql.iMsqlDriver();
// This creates a new instance of the Driver we want to use. There are a
// number of ways to specify which driver you want to use, and there is
// even a way to let the JDBC DriverManager choose which driver it
thinks
// it needs to connect to the data source.
return true;
}
return false;
} // handleEvent() end
No Guts, No Glory: Executing Queries And Processing Results
Now that we have opened the connection to the data source (Listing 4.6), its time to set
up the mechanism for executing queries and getting the results, as shown in Listings 4.7
and 4.8. The parameter that we need in this method is a String containing the SQL query
the user entered into the QueryField. We will return the results of the query as a string
because we only want to pipe all of the results into the OutputField TextArea. We cast
34
all of the returned results into a Stringhowever, if the database contains binary data, we
could get some weird output, or even cause the program to break. When I tested the
applet, the data source that I queried contained numerical and strings only. In Chapter 7,
Ill show you how to deal with different data types in the ANSI SQL-2 specification,
upon which the data types for the JDBC are based.
Listing 4.7 Executing a statement.
public String Select(String QueryLine) {
// This is the method we called above in Listing 4.5.
// We return a String, and use a String parameter for the entered query.
String Output="";
int columns;
int pos;
try {
// Several of the following methods can throw exceptions if there was a
// problem with the query, or if the connection breaks, or if
// we improperly try to retrieve results.
ResultSet rs = stmt.executeQuery(QueryLine);
// The ResultSet in turn is linked to the connection to the data source
// via the Statement class. The Statement class contains the
executeQuery
// method, which returns a ResultSet class. This is analagous to a
// pointer that can be used to retrieve the results from the JDBC
// connection.
columns=(rs.getMetaData()).getColumnCount();
// Here we use the getMetaData method in the result set to return a
// Metadata object. The MetaData object contains a getColumnCount
// method which we use to determine how many columns of data
// are present in the result. We set this equal to an integer
// variable.
Listing 4.8 Getting the Result and MetaData Information.
while(rs.next()) {
// Now, we use the next method of the ResultSet instance rs to fetch
// each row, one by one. There are more optimized ways of doing
// this--namely using the inputStream feature of the JDBC driver.
// I show you an example of this in Chapter 9.
Output+=rs.getObject(pos)+" ";
// Here we've used the general method for getting a result. The
// getObject method will attempt to caste the result in the form
// of its assignee, in this case the String variable Output.
35
// We simply get each "cell" and add a space to it, then append it onto
// the Output variable.
}
// End for loop (end looping through the columns for a specific row ).
Output+="\n";
// For each row that we fetch, we need to add a carriage return so that
// the next fetched row starts on the next line.
}
// End while loop ( end fetching rows when no more rows are left ).
stmt.close();
// Clean up, close the stmt, in effect, close the input-output query
// connection streams, but stay connected to the data source.
}
catch( Exception e ) {
e.printStackTrace();
Output=e.getMessage();
}
// We have to catch any exceptions that were thrown while we were
// querying or retrieving the data. Print the exception
// to the console and return it so it can be shown to the user
// in the applet.
return Output;
// Before exiting, return the result that we got.
}
Wrapping It Up
The last part of the applet, shown in Listing 4.9, involves terminating the connection to
the data source. This is done in the destroy method of the applet. We have to catch an
exception, if one occurs, while the close method is called on the connection.
Listing 4.9 Terminating the connection.
public void destroy() {
try {con.close();}
catch( Exception e ) {
e.printStackTrace();
System.out.println(e.getMessage());
}
} // end destroy
} // end applet
36
Listing 4.10 HTML code to call the interactive query applet.
<HTML>
<HEAD>
<TITLE>JDBC Client Applet - Interactive SQL Command Util</TITLE>
</HEAD>
<BODY>
<H1>Interactive JDBC SQL Query Applet</H1>
<hr>
<hr>
</BODY>
</HTML>
37
Dont forget, if you have problems finding the class file or the driver, set the
CLASSPATH. See Chapter 3 for more help on this topic.
Coming Up Next
In the next chapter, well explore the bridge between ODBC and JDBC. Youll see how
easy it is to use existing ODBC drivers with JDBC, and learn some of the fine points of
the relation, similarity, and difference between the two database connectivity standards.
You wont want to miss this one; the author, Karl Moss, is also the author of the
Sun/Intersolv ODBC-JDBC bridge included in the JDBC package.
Chapter 5
Accessing ODBC Services Using JDBC
One of JavaSofts first tasks in developing the JDBC API was to get it into the hands of
developers. Defining the API specification was a major step, but JDBC drivers must be
implemented in order to actually access data. Because ODBC has already established
itself as an industry standard, what better way to make JDBC usable by a large
community of developers than to provide a JDBC driver that uses ODBC. JavaSoft
turned to Intersolv to provide resources to develop a bridge between the two, and the
resulting JDBC driverthe Bridgeis now included with the Java Developers kit.
The Bridge works great, but there are some things you need to understand before you can
implement it properly. In this chapter, well cover the requirements necessary to use the
Bridge, the limitations of the Bridge, and the most elegant way to make a connection to a
JDBC URL. Ill also provide you with a list of each JDBC method and the corresponding
ODBC call (broken down by the type of call).
Bridge Requirements
One thing to note about the JDBC-ODBC Bridge is that it contains a very thin layer of
native code. This librarys sole purpose is to accept an ODBC call from Java, execute that
call, and return any results back to the driver. There is no other magic happening within
this library; all processing, including memory management, is contained within the Java
side of the Bridge. Unfortunately, this means that there is a library containing C code that
must be ported to each of the operating systems that the Bridge will execute on. This is
obviously not an ideal situation, and invalidates one of Javas major advantages
portability. So, instead of being able to download Java class files and execute on the fly,
you must first install and configure additional software in order to use the Bridge. Heres
a short checklist of required components:
The Java Developers Kit
The JDBC Interface classes (java.sql.*)
The JDBC-ODBC Bridge classes (jdbc.odbc.* or
sun.jdbc.odbc.* for JDBC version 1.1 and higher)
38
An ODBC Driver Manager (such as the one provided
by Microsoft for Win95/NT); do not confuse this with
the JDBC DriverManager class
Any ODBC drivers to be used from the Bridge (from
vendors such as Intersolv, Microsoft, and Visigenic)
Before actually attempting to use the Bridge, save yourself lots of headachesbe sure to
test the ODBC drivers that you will be using! I have pursued countless reported problems
that ended up being nothing more than an ODBC configuration issue. Make sure you
setup your data sources properly, and then test them to make sure you can connect and
perform work. You can accomplish this by either using an existing tool or writing your
own sample ODBC application. Most vendors include sample source code to create an
ODBC application, and Microsoft provides a tool named Gator (a.k.a ODBCTE32.EXE)
which can fully exercise ODBC data sources on Win95/NT.
39
applets can only access databases on the server from which they were downloaded.
Normally, the Java Security Manager will prohibit a TCP connection from being made to
an unauthorized hostname; that is, if the TCP connection is being made from within the
Java Virtual Machine (JVM). In the case of the Bridge, this connection would be made
from within the ODBC driver, outside the control of the JVM. If the Bridge could
determine the hostname that it will be connected to, a call to the Java Security Manager
could easily check to ensure that a connection is allowed. Unfortunately, it is not always
possible to determine the hostname for a given ODBC data source name. For this reason,
the Bridge always assumes the worst. An untrusted applet is not allowed to access any
ODBC data source. What this means is that if you cant convince the Internet browser in
use that an applet is trusted, you cant use the Bridge from that applet.
The Bridge can only provide services for URLs that have a subprotocol of odbc. If a
different subprotocol is given, the Bridge will simply tell the JDBC DriverManager that
it has no idea what the URL means, and that it cant support it. The subname specifies the
ODBC data source name to use, followed by any additional connection string attributes.
Heres a code snippet that you can use to connect to an ODBC data source named
Accounting, with a user name of dept12 and a password of Julie:
// Create a new instance of the JDBC-ODBC Bridge.
new jdbc.odbc.JdbcOdbcDriver();
// The JDBC-ODBC Bridge will have registered itself with the JDBC
// DriverManager. We can now let the DriverManager choose the right
// driver to connect to the given URL.
40
public static synchronized Connection getConnection(String url);
public static synchronized Connection getConnection(String url,
java.util.Properties info);
The third method listed here is by far the most elegant way of connecting to any JDBC
driver. An intelligent Java application/applet will use Driver.getPropertyInfo (which
will not be covered here) to get a list of all of the required and optional properties for the
driver. The Java program can then prompt the user for this information, and then create a
java.util.Properties object that contains an element for each of the driver properties to
be used for the JDBC connection. The following code shows how to setup the
java.util.Properties object:
// Create the Properties object.
prop.put("UID", "dept12");
prop.put("PWD", "Julie");
41
attribute given
Each property returned is converted into a
DriverPropertyInfo object
42
fOption =
isReadOnly SQLGetConnectOption
SQL_ACCESS_MODE
setCatalog SQLSetConnectOption fOption =
SQL_CURRENT_
QUALIFIER
getCatalog SQLGetInfo fInfoType =
SQL_DATABASE_NAME
fOption =
setTransactionIsolation SQLSetConnectOption
SQL_TXN_ISOLATION
fOption =
getTransactionIsolation SQLGetConnectOption
SQL_TXN_ISOLATION
setAutoClose ODBC does not
provide a method to
modify this behavior
fInfoType = SQL_CURSOR_COMMIT_
BEHAVIOR and fInfoType = SQL_CURSOR_
ROLLBACK_BEHAVIOR; the Bridge makes both calls, and if either are
true, then getAutoClose returns true
43
SQL_NULL_COLLATION; res
must be SQL_NC_START
nullsAreSortedAtEnd SQLGetInfo fInfoType =
SQL_NULL_COLLATION; res
must be SQL_NC_END
getDatabaseProductName SQLGetInfo fInfoType = SQL_DBMS_NA
getDatabaseProductVersion SQLGetInfo fInfoType = SQL_DBMS_VE
usesLocalFiles SQLGetInfo fInfoType = SQL_FILE_USAG
the result must be
SQL_FILE_QUALIFIER
usesLocalFilePerTable SQLGetInfo fInfoType = SQL_FILE_USAG
the result must be
SQL_FILE_TABLE
supportsMixedCaseIdentifiers SQLGetInfo fInfoType =
SQL_IDENTIFIER_CASE; th
result must be SQL_IC_UPP
SQL_IC_LOWER or
SQL_IC_MIXED
storesUpperCaseIdentifiers SQLGetInfo fInfoType =
SQL_IDENTIFIER_CASE, th
result must be SQL_IC_UPP
storesLowerCaseIdentifiers SQLGetInfo fInfoType =
SQL_IDENTIFIER_CASE; th
result must be SQL_IC_LOW
storesMixedCaseIdentifiers SQLGetInfo fInfoType =
SQL_IDENTIFIER_CASE; th
result must be SQL_IC_MIX
supportsMixedCaseQuoted SQLGetInfo fInfoType =
Identifiers SQL_QUOTED_IDENTIFIER_C
the result must be
SQL_IC_UPPER, SQL_IC_LOW
or SQL_IC_MIXED
storesUpperCaseQuoted SQLGetInfo fInfoType =
Identifiers SQL_QUOTED_IDENTIFIER_C
the result must be
SQL_IC_UPPER
storesLowerCaseQuoted SQLGetInfo fInfoType =
Identifiers SQL_QUOTED_IDENTIFIER_C
the result must be
SQL_IC_LOWER
44
storesMixedCaseQuoted SQLGetInfo fInfoType =
Identifiers SQL_QUOTED_IDENTIFIER_C
the result must be
SQL_IC_MIXED
getIdentifierQuoteString SQLGetInfo fInfoType =
SQL_IDENTIFIER_QUOTE_CH
getSQLKeywords SQLGetInfo fInfoType = SQL_KEYWORD
getNumericFunctions SQLGetInfo fInfoType =
SQL_NUMERIC_FUNCTIONS;
result is a bitmask enumera
the scalar numeric function
this bitmask is used to crea
comma-separated list of
functions
getStringFunctions SQLGetInfo fInfoType =
SQL_STRING_FUNCTIONS;
result is a bitmask enumera
the scalar string functions;
bitmask is used to create
comma-separated list of
functions
getSystemFunctions SQLGetInfo fInfoType = SQL_SYSTEM
FUNCTIONS; the result is
bitmask enumerating the sc
system functions; this bitma
used to create a comma-
separated list of function
getTimeDateFunctions SQLGetInfo fInfoType = SQL_TIMEDAT
FUNCTIONS; the result is
bitmask enumerating the sc
date and time functions; T
bitmask is used to create
comma-separated list of
functions
getSearchStringEscape SQLGetInfo fInfoType =
SQL_SEARCH_PATTERN_
ESCAPE
getExtraNameCharacters SQLGetInfo fInfoType = SQL_SPECIAL
CHARACTERS
supportsAlterTableWithAdd SQLGetInfo fInfoType = SQL_ALTER_TAB
Column result must have the
45
SQL_AT_ADD_COLUMN bit
supportsAlterTableWithDrop SQLGetInfo fInfoType =SQL_ALTER_TAB
Column the result must have the
SQL_AT_DROP_
COLUMN bit set
supportsColumnAliasing SQLGetInfo fInfoType = SQL_COLUMN_A
nullPlusNonNullIsNull SQLGetInfo fInfoType =
SQL_CONCAT_NULL_BEHAVI
the result must be SQL_CB_N
supportsConvert SQLGetInfo fInfoType = SQL_CONVERT
FUNCTIONS; the result must
SQL_FN_CVT_CONVERT
supportsTableCorrelation SQLGetInfo fInfoType = SQL_CORRELATI
Names NAME; the result must be
SQL_CN_
DIFFERENT or SQL_CN_AN
supportsDifferentTable SQLGetInfo fInfoType = SQL_CORRELATI
CorrelationNames NAMES; the result must b
SQL_CN_
DIFFERENT
supportsExpressionsIn SQLGetInfo fInfoType = SQL_EXPRESSIO
OrderBy IN_ORDER_BY
supportsOrderByUnrelated SQLGetInfo fInfoType = SQL_ORDER_B
COLUMNS_IN_SELECT
supportsGroupBy SQLGetInfo fInfoType = SQL_GROUP_BY;
result must not be
SQL_GB_NOT_
SUPPORTED
supportsGroupByUnrelated SQLGetInfo fInfoType = SQL_GROUP_BY;
result must be SQL_GB_NO
RELATION
supportsGroupByBeyond SQLGetInfo fInfoType = SQL_GROUP_BY;
Select result must be
SQL_GB_GROUP_BY_
CONTAINS_SELECT
supportsLikeEscapeClause SQLGetInfo fInfoType = SQL_LIKE_ESCA
CLAUSE
supportsMultipleResultSets SQLGetInfo fInfoType = SQL_MULT_RESU
SETS
46
supportsMultipleTransactions SQLGetInfo fInfoType = SQL_MULTIPL
ACTIVE_TXN
supportsNonNullableColumns SQLGetInfo fInfoType = SQL_NON_
NULLABLE_COLUMNS; the re
must be SQL_NNC_NON_
NULL
supportsMinimumSQL SQLGetInfo fInfoType = SQL_ODBC_SQ
Grammar CONFORMANCE; result must
SQL_OSC_MINIMUM,
SQL_OSC_CORE, or
SQL_OSC_EXTENDED
supportsCoreSQLGrammar SQLGetInfo fInfoType = SQL_ODBC_
SQL_CONFORMANCE; the re
must be SQL_OSC_CORE o
SQL_OSC_EXTENDED
supportsExtendedSQL SQLGetInfo fInfoType = SQL_ODBC_
Grammar SQL_CONFORMANCE; the re
must be SQL_OSC_
EXTENDED
supportsIntegrityEnhancement SQLGetInfo fInfoType = SQL_ODBC_SQ
Facility OPT_IEF
supportsOuterJoins SQLGetInfo fInfoType = SQL_OUTER_JOI
the result must not be N
supportsFullOuterJoins SQLGetInfo fInfoType = SQL_OUTER_JOI
the result must be F
supportsLimitedOuterJoins SQLGetInfo fInfoType = SQL_OUTER_JOI
the result must be P
getSchemaTerm SQLGetInfo fInfoType = SQL_OWNER_TE
fInfoType =
getProcedureTerm SQLGetInfo
SQL_PROCEDURE_TERM
fInfoType =
getCatalogTerm SQLGetInfo
SQL_QUALIFIER_TERM
isCatalogAtStart SQLGetInfo fInfoType = SQL_QUALIFIE
LOCATION; the result must
SQL_QL_START
getCatalogSeparator SQLGetInfo fInfoType =
SQL_QUALIFIER_NAME_
SEPARATOR
supportsSchemasInData SQLGetInfo fInfoType =
47
Manipulation SQL_OWNER_USAGE; the re
must have the SQL_OU_DM
STATEMENTS bit set
supportsSchemasInProcedure SQLGetInfo fInfoType =
Calls SQL_OWNER_USAGE; the re
must have the SQL_OU_
PROCEDURE_INVOCATION bi
supportsSchemasInTable SQLGetInfo fInfoType =
Definitions SQL_OWNER_USAGE; the re
must have the SQL_OU_TAB
DEFINITION bit set
supportsSchemasInIndex SQLGetInfo fInfoType =
Definitions SQL_OWNER_USAGE; the re
must have the SQL_OU_IND
DEFINITION bit set
supportsSchemasInPrivilege SQLGetInfo fInfoType =
Definitions SQL_OWNER_USAGE; the re
must have the SQL_OU_
PRIVILEGE_DEFINITION bit
supportsCatalogsInData SQLGetInfo fInfoType =
Manipulation SQL_QUALIFIER_USAGE; t
result must have the
SQL_QU_DML_STATEMENTS
set
supportsCatalogsInProcedure SQLGetInfo fInfoType =
Calls SQL_QUALIFIER_USAGE; t
result must have the SQL_Q
PROCEDURE_INVOCATION bi
supportsCatalogsInTable SQLGetInfo fInfoType = SQL_QUALIFIE
Definitions USAGE; the result must have
SQL_QU_TABLE_DEFINITION
set
supportsCatalogsInIndex SQLGetInfo fInfoType =
Definitions SQL_QUALIFIER_USAGE; t
result must have the
SQL_QU_INDEX_DEFINITION
set
supportsCatalogsInPrivilege SQLGetInfo fInfoType =
Definitions SQL_QUALIFIER_USAGE; t
result must have the SQL_Q
PRIVILEGE_DEFINITION bit
48
supportsPositionedDelete SQLGetInfo fInfoType = SQL_POSITIONE
STATEMENTS; the result m
have the
SQL_PS_POSITIONED_DELET
set
supportsPositionedUpdate SQLGetInfo fInfoType = SQL_POSITIONE
STATEMENTS; the result m
have the
SQL_PS_POSITIONED_UPDA
bit set
supportsSelectForUpdate SQLGetInfo fInfoType = SQL_POSITIONE
STATEMENTS; the result m
have the
SQL_PS_SELECT_FOR_UPDA
bit set
supportsStoredProcedures SQLGetInfo fInfoType = SQL_PROCEDUR
supportsSubqueriesIn SQLGetInfo fInfoType = SQL_SUBQUERI
Comparisons the result must have the
SQL_SQ_
COMPARISON bit set
supportsSubqueriesInExists SQLGetInfo fInfoType = SQL_SUBQUERI
the result must have the
SQL_SQ_EXISTS bit set
supportsSubqueriesInIns SQLGetInfo fInfoType = SQL_SUBQUERI
the result must have the
SQL_SQ_IN bit set
supportsSubqueriesIn SQLGetInfo fInfoType = SQL_SUBQUERI
Quantifieds the result must have the
SQL_SQ_
QUANTIFIED bit set
supportsCorrelatedSubqueries SQLGetInfo fInfoType = SQL_SUBQUERI
the result must have the
SQL_SQ_
CORRELATED_SUBQUERIES
set
supportsUnion SQLGetInfo fInfoType = SQL_UNION; t
result must have the
SQL_U_UNION bit set
supportsUnionAll SQLGetInfo fInfoType = SQL_UNION; t
result must have the
49
SQL_U_UNION_ALL bit se
supportsOpenCursors SQLGetInfo fInfoType =
Across Commit SQL_CURSOR_COMMIT_
BEHAVIOR; the result must
SQL_CB_PRESERVE
supportsOpenCursors SQLGetInfo fInfoType = SQL_CURSOR
Across Rollback ROLLBACK_BEHAVIOR; the re
must be SQL_CB_PRESERV
supportsOpenStatements SQLGetInfo fInfoType = SQL_CURSOR
Across Commit COMMIT_BEHAVIOR; the res
must be SQL_CB_PRESERVE
SQL_CB_CLOSE
supportsOpenStatements SQLGetInfo fInfoType = SQL_CURSOR
Across Rollback ROLLBACK_BEHAVIOR; the re
must be SQL_CB_PRESERVE
SQL_CB_CLOSE
getMaxBinaryLiteralLength SQLGetInfo fInfoType = SQL_MAX_BINA
LITERAL_LEN
getMaxCharLiteralLength SQLGetInfo fInfoType = SQL_MAX_CHA
LITERAL_LEN
getMaxColumnNameLength SQLGetInfo fInfoType = SQL_MAX_COLU
NAME_LEN
getMaxColumnsInGroupBy SQLGetInfo fInfoType =
SQL_MAX_COLUMNS_
IN_GROUP_BY
getMaxColumnsInIndex SQLGetInfo fInfoType =
SQL_MAX_COLUMNS_
IN_INDEX
getMaxColumnsInOrderBy SQLGetInfo fInfoType =
SQL_MAX_COLUMNS_
IN_ORDER_BY
getMaxColumnsInSelect SQLGetInfo fInfoType =
SQL_MAX_COLUMNS_
IN_SELECT
getMaxColumnsInTable SQLGetInfo fInfoType =
SQL_MAX_COLUMNS_
IN_TABLE
getMaxConnections SQLGetInfo fInfoType = SQL_ACTIVE_
CONNECTIONS
50
getMaxCursorNameLength SQLGetInfo fInfoType = SQL_MAX_CURS
NAME_LEN
fInfoType =
getMaxIndexLength SQLGetInfo
SQL_MAX_INDEX_SIZE
getMaxSchemaNameLength SQLGetInfo fInfoType = SQL_MAX_OWN
NAME_LEN
getMaxProcedureNameLength SQLGetInfo fInfoType = SQL_MAX_
PROCEDURE_NAME_LEN
getMaxCatalogNameLength SQLGetInfo fInfoType = SQL_MAX_
QUALIFIER_NAME_LEN
fInfoType =
getMaxRowSize SQLGetInfo
SQL_MAX_ROW_SIZE
doesMaxRowSizeIncludeBlobs SQLGetInfo fInfoType =
SQL_MAX_ROW_SIZE_
INCLUDES_LONG
getMaxStatementLength SQLGetInfo fInfoType = SQL_MAX_
STATEMENT_LEN
getMaxStatements SQLGetInfo fInfoType = SQL_ACTIVE_
STATEMENTS
getMaxTableNameLength SQLGetInfo fInfoType = SQL_MAX_TABL
NAME_LEN
getMaxTablesInSelect SQLGetInfo fInfoType = SQL_MAX_TABL
IN_SELECT
getMaxUserNameLength SQLGetInfo fInfoType = SQL_MAX_USE
NAME_LEN
getDefaultTransactionIsolation SQLGetInfo fInfoType = SQL_DEFAULT_T
ISOLATION
supportsTransactions SQLGetInfo fInfoType = SQL_TXN_CAPAB
the result must not be
SQL_TC_NONE
SQLGetInfo fInfoType =
supportsTransactionIsolation
SQL_TXN_ISOLATION_
Level
OPTION
SQLGetInfo fInfoType = SQL_TXN_CAPAB
supportsDataDefinitionAnd
the result must have the
DataManipulationTransactions
SQL_TC_ALL bit set
supportsDataManipulation SQLGetInfo fInfoType = SQL_TXN_CAPAB
TransactionsOnly the result must have the
SQL_TC_DML bit set
51
dataDefinitionCauses SQLGetInfo fInfoType = SQL_TXN_CAPAB
Transaction Commit the result must have the
SQL_TC_DDL_COMMIT bit s
dataDefinition SQLGetInfo fInfoType = SQL_TXN_CAPAB
IgnoredIn Transactions the result must have the
SQL_TC_DDL_IGNORE bit s
getProcedures SQL Returns a list of procedur
Procedures names
getProcedureColumns SQLProcedure Returns a list of input and ou
Columns parameters used for procedu
getTables SQLTables Returns a list of tables
getSchemas SQLTables Catalog = , Schema = %
Table = , TableType = NU
only the TABLE_SCHEM colum
returned
getCatalogs SQLTables Catalog = %, Schema =
Table = , TableType = NU
only the TABLE_CAT column
returned
getTableTypes SQLTables Catalog = , Schema = , T
= , TableType = %
getColumns SQLColumns Returns a list of column nam
in specified tables
getColumnPrivileges SQLColumn Returns a list of columns a
Privileges associated privileges for th
specified table
getTablePrivileges Returns a list of tables and
SQLTable
privileges associated with e
Privileges
table
getBestRowIdentifier SQLSpecial fColType = SQL_BEST_ROW
Columns
getVersionColumns SQLSpecial fColType = SQL_ROWVER
Columns
getPrimaryKeys SQLPrimary Returns a list of column nam
Keys that comprise the primary k
for a table
getImportedKeys SQLForeign PKTableCatalog = NULL,
Keys PKTableSchema = NULL,
PKTableName = NULL
52
getExportedKeys SQLForeign FKTableCatalog = NULL,
Keys FKTableSchema = NULL,
FKTableName = NULL
getCrossReference SQLForeign Returns a list of foreign key
Keys the specified table
SQLGetType
getTypeInfo fSqlType = SQL_ALL_TYPE
Info
Returns a list of statistics about the specified table and the indexes associ
with the table
Table 5.4
Statement ODBC
calls. JDBC
Interface Method
ODBC Call Comments
close SQLFreeStmt fOption = SQL_CLOSE
fOption =
getMaxFieldSize SQLGetStmtOption
SQL_MAX_LENGTH
fOption =
setMaxFieldSize SQLSetStmtOption
SQL_MAX_LENGTH
fOption =
getMaxRows SQLGetStmtOption
SQL_MAX_ROWS
fOption =
setMaxRows SQLSetStmtOption
SQL_MAX_ROWS
fOption =
setEscapeProcessing SQLSetStmtOption
SQL_NOSCAN
getQueryTimeout SQLGetStmtOption fOption =
SQL_QUERY_TIMEOUT
setQueryTimeout SQLSetStmtOption fOption =
SQL_QUERY_TIMEOUT
cancel SQLCancel Cancels the
processing on a
statement
setCursorName SQLSetCursorName Associates a cursor
name with a
statement
execute SQLExecDirect The Bridge checks for
53
a SQL statement
containing a FOR
UPDATE clause; if
present, the cursor
concurrency level for
the statement is
changed to
SQL_CONCUR_LOCK
getUpdateCount SQLRowCount Returns the number
of rows affected by
an UPDATE, INSERT,
or DELETE statement
Determines whether there are more results available on a
statement and, if so, initializes processing for those results
Table 5.5
PreparedStatement
ODBC calls. JDBC
Interface Method
ODBC Call Comments
setNull SQLBindParameter fParamType =
SQL_PARAM_INPUT;
fSqlType = sqlType
passed as parameter
setBoolean
setByte
setShort
setInt
setLong
setFloat
setDouble
setNumeric
setString
setBytes
setDate
setTime
setTimestamp SQLBindParameter fParamType =
SQL_PARAM_INPUT;
54
fSqlType is derived by
the type of get
method
setAsciiStream
setUnicodeStream
setBinaryStream SQLBindParameter fParamType =
SQL_PARAM_INPUT,
pcbValue =
SQL_DATA_AT_EXEC
May return SQL_NEED_DATA (because of setAsciiStream,
setUnicodeStream, or setBinary Stream); in this case, the
Bridge will call SQLParamData and SQLPutData until no more
data is needed
Table 5.6
CallableStatement
ODBC calls. JDBC
Interface
Method
ODBC Call Comments
fParamType = SQL_PARAM_OUTPUT; rgbValue is a buffer
that has been allocated in Java; when using the getXXX
methods, this buffer is used to retrieve the data
Table 5.7
ResultSet ODBC
calls. JDBC
Interface
Method
ODBC Call Comments
next SQLFetch Fetches a row of data
from a ResultSet
close SqlFreeStmt fOption = SQL_CLOSE
getString
getBoolean
getByte
getShort
getInt
55
getLong
getFloat
getDouble
getNumeric
getBytes
getTime
getTimestamp SQLGetData fCType is derived by
the type of get method
getAsciiStream
getUnicodeStream
getBinaryStream SQLGetData An InputStream object
is created to provide a
wrapper around the
SQLGetData call; data
is read from the data
source as needed
Returns the cursor name associated with the statement
Table 5.4
Statement ODBC
calls. JDBC
Interface Method
ODBC Call Comments
close SQLFreeStmt fOption = SQL_CLOSE
fOption =
getMaxFieldSize SQLGetStmtOption
SQL_MAX_LENGTH
fOption =
setMaxFieldSize SQLSetStmtOption
SQL_MAX_LENGTH
fOption =
getMaxRows SQLGetStmtOption
SQL_MAX_ROWS
fOption =
setMaxRows SQLSetStmtOption
SQL_MAX_ROWS
fOption =
setEscapeProcessing SQLSetStmtOption
SQL_NOSCAN
getQueryTimeout SQLGetStmtOption fOption =
SQL_QUERY_TIMEOUT
56
setQueryTimeout SQLSetStmtOption fOption =
SQL_QUERY_TIMEOUT
cancel SQLCancel Cancels the
processing on a
statement
setCursorName SQLSetCursorName Associates a cursor
name with a
statement
execute SQLExecDirect The Bridge checks for
a SQL statement
containing a FOR
UPDATE clause; if
present, the cursor
concurrency level for
the statement is
changed to
SQL_CONCUR_LOCK
getUpdateCount SQLRowCount Returns the number
of rows affected by
an UPDATE, INSERT,
or DELETE statement
Determines whether there are more results available on a
statement and, if so, initializes processing for those results
Table 5.5
PreparedStatement
ODBC calls. JDBC
Interface Method
ODBC Call Comments
setNull SQLBindParameter fParamType =
SQL_PARAM_INPUT;
fSqlType = sqlType
passed as parameter
setBoolean
setByte
setShort
setInt
setLong
setFloat
57
setDouble
setNumeric
setString
setBytes
setDate
setTime
setTimestamp SQLBindParameter fParamType =
SQL_PARAM_INPUT;
fSqlType is derived by
the type of get
method
setAsciiStream
setUnicodeStream
setBinaryStream SQLBindParameter fParamType =
SQL_PARAM_INPUT,
pcbValue =
SQL_DATA_AT_EXEC
May return SQL_NEED_DATA (because of setAsciiStream,
setUnicodeStream, or setBinary Stream); in this case, the
Bridge will call SQLParamData and SQLPutData until no more
data is needed
Table 5.6
CallableStatement
ODBC calls. JDBC
Interface
Method
ODBC Call Comments
fParamType = SQL_PARAM_OUTPUT; rgbValue is a buffer
that has been allocated in Java; when using the getXXX
methods, this buffer is used to retrieve the data
Table 5.7
ResultSet ODBC
calls. JDBC
Interface
Method
ODBC Call Comments
58
next SQLFetch Fetches a row of data
from a ResultSet
close SqlFreeStmt fOption = SQL_CLOSE
getString
getBoolean
getByte
getShort
getInt
getLong
getFloat
getDouble
getNumeric
getBytes
getTime
getTimestamp SQLGetData fCType is derived by
the type of get method
getAsciiStream
getUnicodeStream
getBinaryStream SQLGetData An InputStream object
is created to provide a
wrapper around the
SQLGetData call; data
is read from the data
source as needed
Returns the cursor name associated with the statement
Chapter 6
SQL Data Types In Java And ORM
Many of the standard SQL-92 data types, such as Date, do not have a native Java
equivalent. To overcome this deficiency, you must map SQL data types into Java. This
process involves using JDBC classes to access SQL data types. In this chapter, well take
a look at the classes in the JDBC that are used to access SQL data types. In addition,
well briefly discuss the Object Relation Model (ORM), an interesting area in database
development that attempts to map relational models into objects.
59
You need to know how to properly retrieve equivalent Java data typeslike int, long,
and Stringfrom their SQL counterparts and store them in your database. This can be
especially important if you are working with numeric data (which requires careful
handling of decimal precision) and SQL timestamps (which have a well-defined format).
The mechanism for handling raw binary data is touched on in this chapter, but it is
covered in more detail in Chapter 8.
The byte[] data type is a byte array of variable size. This data structure is used to store
binary data; binary data is manifest in SQL as VARBINARY and LONGVARBINARY.
These types are used to store images, raw document files, and so on. To store or retrieve
this data from the database, you would use the stream methods available in the JDBC:
setBinaryStream and getBinaryStream. In Chapter 8, well use these methods to build
a multimedia Java/JDBC application.
Table 6.2 shows the mapping of SQL data types into Java. You will find that both tables
will come in handy when youre attempting to decide which types need special treatment.
60
You can also use the tables as a quick reference to make sure that youre properly casting
data that you want to store or retrieve.
Table 6.2 SQL data
type mapping into Java
SQL Type
and JDBC. Java Type
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.sql.Nueric
DECIMAL java.sql.Numeric
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE souble
BINARY byte[]
VARBINARY byte[]
LONGBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
java.sql.Timestamp
Now that youve seen how these data types translate from Java to SQL and vice versa,
lets look at some of the methods that youll use to retrieve data from a database. These
methods, shown in Table 6.3, are contained in the ResultSet class, which is the class that
is passed back when you invoke a Statement.executeQuery function. Youll find a
complete reference of the ResultSet class methods in Chapter 12.
The parameters int and String allow you to specify the column you want by column
number or column name.
Table 6.3 A few ResultSet
methods for getting data. Description
Method
61
getAsciiStream(String), Retrieves a column value as a
getAsciiStream(int) stream of ASCII characters
and then reads in chunks
from the stream
getBinaryStream(int), Retrieves a column value as a
getBinaryStream(String) stream of uninterpreted bytes
and then reads in chunks
from the stream
getBoolean(int), Returns the value of a column
getBoolean(String) in the current row as a Java
boolean
getDate(int), getDate(String) Returns the value of a column
in the current row as a
java.sql.Date object
Returns the value of a column as a Java object
ResultSetMetaData
One of the most useful classes you can use to retrieve data from a ResultSet is the
ResultSetMetaData class. This class contains methods that allow you to obtain vital
information about the querys result. After a query has been executed, you can call the
ResultSet.getMetaData method to fetch a ResultSetMetaData object for the resulting
data. Table 6.4 shows some of the methods that you will most likely use. Again, more
ResultSetMetaData methods are listed in Chapter 12.
Table 6.4 Handy
methods in the
ResultSetMetaData Description
class. Method
62
contain NULLs
Indicates whether the specified column is searchable via a
WHERE clause
63
these kinds of object-oriented/relational bridges. Moreover, there are several solutions
being developed to work specifically with Java.
Ive given you an idea of what ORM is all about. If you would like to investigate this
topic further, check out The Coriolis Group Web site (http://www.coriolis.com/jdbc-
book) for links to ORM vendors and some really informative ORM documents. The
ODMG (Object Database Management Group) is a consortium that is working on a
revised standard for object database technology and the incorporation of this concept into
programming languages such as Java. A link to the consortiums Web site can be found
on The Coriolis Group Web site as well.
Summary
As you can see from this brief chapter, mapping SQL data types to Java is truly a snap.
We covered a few of the more important methods you will use to retrieve data from a
database. For a complete reference, see Chapter 12 and have a look at the Date, Time,
TimeStamp, Types, and Numeric classes.
The next chapter steps back from the JDBC to look at ways of presenting your data in
Java. Using Java packages available on the Net, well cover graphs, tables, and more.
Well also discuss some nifty methods in the JDBC that will help streamline your code
for retrieving data from your database.
Chapter 7
Working With Query Results
So far, weve been concentrating on how to use the classes in the JDBC to perform SQL
queries. Thats great, but now we have to do something with the data weve retrieved.
The end user of your JDBC applets or applications will want to see more than just rows
and rows of data. In this chapter, well learn how to package the raw table data that is
returned after a successful SQL query into a Java object, and then how to use this
packaged data to produce easy-to-read graphs.
The first issue well look at is creating a Java object to store the results of a query. This
object will provide a usable interface to the actual query results so they can be plugged
into a Java graphics library. Well create a simple data structure to hold the column
results in a formatted way so that we can easily parse them and prepare them for display.
Second, well look at taking these results in the Java object and setting up the necessary
code to plug the data into a pie chart and bar graph Java package.
In the next chapter, well go one step further and work with BLOB data types (like
images). Between these chapters, I will be providing plenty of examples, complete with
code, to help you work up your own JDBC programs. At the very least, these chapters
will give you some ideas for dealing with raw table data and displaying it in an effective
manner.
64
A Basic Java Object For Storing Results
Although the JDBC provides you with the ResultSet class to get the data from an SQL
query, you will still need to store and format within your program the results for display.
The smart way to do this is in a re-usable fashion (by implementing a generic object or
class) which allows you to re-use the same class you develop to retrieve data from a
query in any of your JDBC programs. The code snippet in Listing 7.1 is a method that
will keep your results in a Java object until you are ready to parse and display it.
Lets begin by defining the data we will be getting from the source, and determining how
we want to structure it within our Java applet. Remember that the ResultSet allows us to
retrieve data in a row-by-row, column-by-column fashion; it simply gives us sequential
access to the resulting table data. Table 7.1 shows the example table we will be using in
this chapter.
Table 7.1
Example table.
first_name last_name salary
emp_no
The optimal way to store this data in our Java program is to put each columns data in its
own structure and then link the different columns by using an index; this will allow us to
keep the columnar relationship of the table intact. We will put each columns data in an
array. To simplify matters, well use the getString method, which translates the different
data types returned by a query into a String type. Then, well take the data in a column
and delimit the instances with commas. Well use an array of String to do this; each place
in the array will represent a different column. The data object we will create is shown
here:
table_data[0] => 01234,1235,0002,0045,0067
table_data[1] => Pratik,Karl,Keith,Ron,David
table_data[2] => Patel,Moss,Weiskamp,Pronk,Friedel
table_data[3] => 8000,23000,90000,59999,53000
Listing 7.1 shows the method well use to query the database and return a String array
that contains the resulting table data.
Listing 7.1 The getData method.
public String[] getData( String QueryLine ) {
// Run the QueryLine SQL query, and return the resulting columns in an
// array of String. The first column is at index [0], the second at [1],
// etc.
65
int columns, pos;
String column[]=new String[4];
// We have to initialize the column String variable even though we re-
// declare it below. The reason is because the declaration below is in a
// try{} statement, and the compiler will complain that the variable may
// not be initialized.
boolean more;
try {
ResultSet rs = stmt.executeQuery(QueryLine);
// Execute the passed in query, and get
// the ResultSet for the query.
columns=(rs.getMetaData()).getColumnCount();
// Get the number of columns in the resulting table so we can
// declare the column String array, and so we can loop
// through the results and retrieve them.
more=rs.next();
// Get the first row of the ResultSet. Loop through the
ResultSet
// and get the data, row-by-row, column-by-column.
while(more) {
more=rs.next();
// Get the next row of the result if it exists.
66
}
}
}
stmt.close();
// All done. Close the statement object.
}
catch( Exception e ) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return column;
// Finally, return the entire column[] array.
}
Showing The Results
Now that we have the data nicely packaged into our Java object, how do we show it? The
code in Listing 7.2 dumps the data in the object to the screen. We simply loop through
the array and print the data.
Listing 7.2 Code to print retrieved data to the console.
public void ShowFormattedData(String[] columnD ) {
int i;
67
Example 7-1
*/
import java.awt.*;
import java.applet.Applet;
import java.sql.*;
ConnectToDB();
// Connect to the database.
add("North", OutputField);
// Add the TextArea for showing the data to the user
String columnData[] = getData("select * from Employee");
// Run a query that goes and gets the complete table listing; we can
put
// any query here and would optimally want to get only the columns we
// need.
ShowFormattedData(columnData);
// Show the data in the TextArea
ShowChartData(columnData[3],columnData[2]);
// Now, pass the two data sets and create a bar chart
add("Center", bar);
// And add the bar chart to the applet's panel
}
int i;
try {
new imaginary.sql.iMsqlDriver();
con = DriverManager.getConnection(url, "prpatel", "");
}
catch( Exception e ) {
68
e.printStackTrace();
System.out.println(e.getMessage());
}
bar.init();
bar.start();
// Initialize it, and start it running.
bar.loadParams(
"Header = ('Salary Information');"+
"DataSets = ('Salary', red);"+
"DataSet1 = "+ Data1 + ";"+
"BarLabels = "+ Data2 + ";"+
"GraphLayout= HORIZONTAL;"+
"BottomAxis = (black, 'TimesRoman', 14, 0,
0,100000)"
);
bar.loadParams ("Update");
// Tell the bar chart class we've put
// some new parameters in.
} catch (Exception e) {
System.out.println (e.getMessage());
}
try {
69
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(QueryLine);
columns=(rs.getMetaData()).getColumnCount();
column = new String[columns];
more=rs.next();
while(more) {
more=rs.next();
for (pos=1; pos<=columns; pos++) {
if(more) {
column[pos-1]+=(",");
}
}
}
stmt.close();
}
catch( Exception e ) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return column;
}
Thats it! Weve successfully queried a database, formatted the resulting data, and created
a bar chart to present a visual representation of the results. Listing 7.5 shows the
generation of a pie chart, and Figure 7.2 shows the pie chart applet.
70
import java.awt.*;
import java.applet.Applet;
import java.sql.*;
import java.util.StringTokenizer;
ConnectToDB();
add("North", OutputField);
String columnData[] = getData("select * from Cost");
ShowFormattedData(columnData);
ShowChartData(columnData[1],columnData[0]);
add("Center", pie);
try {
new imaginary.sql.iMsqlDriver();
con = DriverManager.getConnection(url, "prpatel", "");
}
catch( Exception e ) {
e.printStackTrace();
System.out.println(e.getMessage());
}
int i;
71
// We need to assign colors to the pie slices automatically, so we use a
// class that cycles through colors. See this class defined below.
while(nData.hasMoreTokens()) {
// Loop through the dataNumber and dataLabel and build the slice data:
// ( 1234, darkBlue, "Label" ). This is what the pie chart class expects,
// so we must parse our data and put it in this format.
System.out.println(SliceData);
if (nData.hasMoreTokens()) {SliceData += ", ";}
}
try {
// We already instantiated the pie chart
// class(NFPieChartAPP) at the top of the applet.
pie.init();
pie.start();
// Initialize and start the pie chart class.
pie.loadParams(
"Background=(black, RAISED, 4);"+
"Header=('Cost Information (millions)');"+
"LabelPos=0.7;"+
"DwellLabel = ('', black, 'TimesRoman', 16);"+
"Legend = ('Legend', black);"+
"LegendBox = (white, RAISED, 4);"+
"Slices=(12.3, blue, 'Marketing', cyan), (4.6,
antiquewhite, 'Sales'), (40.1, aqua, 'Production'),
(18.4, aquamarine, 'Support');");
pie.loadParams ("Update");
// Tell the pie chart class we've sent it new
// parameters to display.
} catch (Exception e) {
System.out.println (e.getMessage());
72
}
}
// Below is the same as before except for the new ColorGenerator class
// that we needed to produce distinct colors.
try {
more=rs.next();
more=rs.next();
for (pos=1; pos<=columns; pos++) {
if(more) {
column[pos-1]+=(",");
}
}
}
stmt.close();
// con.close();
}
catch( Exception e ) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return column;
}
public void destroy() {
try {con.close();}
catch( Exception e ) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
73
class ColorGenerator {
// This class is needed to produce colors that the pie chart can use to
// color the slices properly. They are taken from the NetCharts color
// class, NFColor.
public ColorGenerator() {
String colors[] =
{"aliceblue","antiquewhite","aqua","aquamarine","azure","beige",
"bisque","black","blanchedalmond","blue","blueviolet","brown","chocolate
",
"cadetblue","chartreuse","cornsilk","crimson","cyan"};
// Increment the color counter, and return a String which contains the
// color at this index.
color_count += 1;
return colors[color_count];
} // end example72.java
Summary
This chapter has shown you how to generate meaningful charts to represent data obtained
from a query. Weve seen how to create both bar and pie charts. You can use the
properties of the NetCharts package to customize your charts as you wish, and there are
many more options in the package that havent been shown in the examples here.
In the next chapter, we will continue to discuss working with database query results, and
we will provide a complete code example for showing SQL BLOB data types. It shows
you how to get an image from the ResultSet, as well as how to add images or binary data
to a table in a database.
Chapter 8
The IconStore Multimedia JDBC Application
74
In the previous chapter, we learned how to process query results with JDBC. In this
chapter, well take these query results and put them to use in a multimedia application.
The application well be developing, IconStore, will connect to a database, query for
image data stored in database tables, and display the images on a canvas. Its all very
simple, and it puts the JDBC to good use by building a dynamic application totally driven
by data stored in tables.
IconStore Requirements
The IconStore application will utilize two database tables: ICONCATEGORY and
ICONSTORE. The ICONCATEGORY table contains information about image
categories, which can be items like printers, sports, and tools. The ICONSTORE table
contains information about each image. Tables 8.1 and 8.2 show the database tables
underlying data structures.
Note that the CATEGORY column in the ICONSTORE is a foreign key into the
ICONCATEGORY table. If the category ID for sports is 1, you can obtain a result set
containing all of the sports images by using this statement:
SELECT ID, DESCRIPTION, ICON FROM ICONSTORE WHERE CATEGORY = 1
Table 8.1 The
ICONCATEGORY
table. Column SQL Type Description
Name
ID INTEGER Image ID
Description of the
DESCRIPTION VARCHAR
image
CATEGORY INTEGER Category ID
Binary image
75
image descriptions in a list box. The ICONSTORE table
is used to dynamically build the list.
The user can select an image description from the
list box to display the corresponding image.
Once an image has been displayed, the user can
select the Save As menu option to save the image to
disk.
As you can see, IconStore will not be too complicated, but it will serve as a very good
foundation for developing database-driven applications.
class BuildDB {
//
// main
//
public static void main(String args[]) {
try {
// Create an instance of the driver
java.sql.Driver d = (java.sql.Driver) Class.forName (
"jdbc.SimpleText.SimpleTextDriver").newInstance();
76
// Close the connection
con.close();
}
catch (SQLException ex) {
System.out.println("\n*** SQLException caught ***\n");
while (ex != null) {
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("Message: " + ex.getMessage());
System.out.println("Vendor: " + ex.getErrorCode());
ex = ex.getNextException ();
}
System.out.println("");
}
catch (java.lang.Exception ex) {
ex.printStackTrace ();
}
}
//
// BuildCategory
// Given a connection object and a table name, create the IconStore
// category database table.
//
protected static void buildCategory(
Connection con,
String table)
throws SQLException
{
System.out.println("Creating " + table);
Statement stmt = con.createStatement();
// Create the SQL statement
String sql = "create table " + table +
" (CATEGORY NUMBER, DESCRIPTION VARCHAR)";
77
// Create the SQL statement
String sql = "create table " + table +
" (ID NUMBER, DESCRIPTION VARCHAR, CATEGORY NUMBER, ICON
BINARY)";
int category;
int id = 1;
//
// AddIconRecord
// Helper method to add an IconStore record. A PreparedStatement is
// provided to which this method binds input parameters. Returns
// true if the record was added.
//
protected static boolean addIconRecord(
PreparedStatement ps,
int id,
String desc,
int category,
String filename)
throws SQLException
{
78
// Create a file object for the icon
File file = new File(filename);
if (!file.exists()) {
return false;
}
// Get the length of the file. This will be used when binding
// the InputStream to the PreparedStatement.
int len = (int) file.length();
FileInputStream inputStream;
try {
// Now execute
int rows = ps.executeUpdate();
return (rows == 0) ? false : true;
}
}
The BuildDB application connects to the SimpleText JDBC driver, creates the
ICONCATEGORY table, adds some image category records, creates the ICONSTORE
table, and adds some image records. Note that when the image records are added to the
ICONSTORE table, a PreparedStatement object is used. Well take a closer look at
PreparedStatements in Chapter 11; for now, just realize that this is an efficient way to
execute the same SQL statement multiple times with different parameters values. Also
note that the image data is coming out of GIF files stored on disk. An InputStream is
created using these files, which is then passed to the JDBC driver for input. The JDBC
driver reads the InputStream and stores the binary data in the database table. Simple,
isnt it? Now that weve created the database, we can start writing our IconStore
application.
Application Essentials
The source code for the IconStore application is shown throughout the rest of this chapter,
broken across the various sections. As always, you can pick up a complete copy of the
source code on the CD-ROM. Remember, you need to have the SimpleText JDBC driver
79
installed before using the IconStore application. See Chapter 3, if you have trouble
getting the application to run.
Writing The main Method
Every JDBC application must have an entry point, or a place at which to start execution.
This entry point is the main method, which is shown in Listing 8.2. For the IconStore
application, main simply processes any command line arguments, creates a new instance
of the IconStore class (which extends Frame, a top-level window class), and sets up the
window attributes. The IconStore application accepts one command line argument: the
location of the IconStore database. The default location is /IconStore.
Listing 8.2 IconStore main method.
import java.awt.*;
import java.io.*;
import java.util.*;
import java.sql.*;
80
IconStore frame = new IconStore();
frame.pack();
frame.resize(300, 400);
frame.show();
}
A lot of work is being performed in IconStore.init, such as establishing the database
connection, reading the icon categories, creating the menus, and reading the icon
descriptions. Well take a look at each of these in greater detail in the following sections.
Establishing The Database Connection
Listing 8.3 shows the code used by the IconStore application to connect to the
SimpleText JDBC driver.
Listing 8.3 Establishing the database connection.
public Connection establishConnection()
{
"jdbc.SimpleText.SimpleTextDriver").newInstance();
81
System.exit(1);
}
catch (java.lang.Exception ex) {
ex.printStackTrace();
System.exit(1);
}
return con;
}
Note that we need to set a property for the SimpleText driver to specify the location of
the database tables. In reality, the SimpleText driver stores each database table as a file,
and the Directory property specifies the directory in which these files are kept. As I
mentioned in the previous section, the default location is /IconStore (the IconStore
directory of your current drive), but this can be overridden to be any location.
If successful, a JDBC Connection object is returned to the caller. If there is any reason a
database connection cannot be established, the pertinent information will be displayed
and the application will be terminated.
try {
// Create a Statement object
Statement stmt = con.createStatement();
82
stmt.close();
}
catch (SQLException ex) {
return table;
}
The flow of this routine is very basic, and well be using it throughout our IconStore
application. First, we create a Statement object; then, we submit an SQL statement to
query the database; next, we process each of the resulting rows; and finally, we close the
Statement. Note that a Hashtable object containing a list of all the categories is
returned; the category description is the key and the category ID is the element. In this
way, we can easily cross-reference a category description to an ID. Well see why this is
necessary a bit later.
Now that all of the category information has been loaded, we can create our menu.
Listing 8.5 shows how this is done.
Listing 8.5 Creating the Icons menu.
// Get a Hashtable containing an entry for each icon category.
// The key is the description and the data value is the
// category number.
categories = getCategories(connection);
// File menu
fileMenu = new Menu("File");
fileMenu.add(new MenuItem("Save As"));
fileMenu.add(new MenuItem("Exit"));
menuBar.add(fileMenu);
// Icons menu
sectionMenu = new Menu("Icons");
Enumeration e = categories.keys();
int listNo = 0;
String desc;
83
// Add the description to the Icons menu
sectionMenu.add(new MenuItem(desc));
}
84
Hashtable table = new Hashtable();
String desc;
try {
// Create a Statement object
Statement stmt = con.createStatement();
category);
}
// Close the statement
stmt.close();
}
catch (SQLException ex) {
return table;
}
The process we used here is the same as we have seen beforecreating a Statement,
executing a query, processing the results, and closing the Statement. Listing 8.7 shows
the entire code for the IconStore.init method. In addition to building the menu, we also
build the CardLayout. It is important to note that the IconStore application is totally
database-driven; no code will have to be modified to add or remove categories or images.
Listing 8.7 IconStore init method.
//
// init
85
// Initialize the IconStore object. This includes reading the
// IconStore database for the icon descriptions.
//
public void init()
{
// Create our canvas that will be used to display the icons
imageCanvas = new IconCanvas();
// File menu
fileMenu = new Menu("File");
fileMenu.add(new MenuItem("Save As"));
fileMenu.add(new MenuItem("Exit"));
menuBar.add(fileMenu);
// Icons menu
sectionMenu = new Menu("Icons");
86
// Get a Hashtable containing an entry for each row found
// for this category. The key is the icon description and
// the data value is the ID.
iconDesc[listNo] = getIconDesc(connection,
(String) categories.get(desc), lists[listNo]);
listNo++;
}
// Add the Icons menu to the menu bar
menuBar.add(sectionMenu);
87
switch (evt.id) {
case Event.ACTION_EVENT:
if (saveFile == null) {
return true;
}
System.exit(0);
}
88
}
}
break;
case Event.LIST_SELECT:
displayIcon(connection);
break;
}
return false;
}
Most of the code is very straightforward. Of interest here is how the CardLayout is
managed. When a user makes a selection from the Icons menu, the selected item (which
is the category description) is used to change the CardLayout. Remember that when the
CardLayout was created, the title of each list was the category description. Also note
that when the user selects an item from the list box (LIST_SELECT), the corresponding
image can be displayed. Listing 8.9 shows how this is done.
When the user selects Exit from the menu, the temporary image file (which is discussed
later) is deleted from disk, and the application is terminated. This is the perfect time to
close the Connection that was in use. I purposefully omitted this step to illustrate a point:
The JDBC specification states that all close operations are purely optional. It is up to the
JDBC driver to perform any necessary clean-up in the finalize methods for each object. I
strongly recommend, though, that all JDBC applications close objects when it is proper to
do so.
Listing 8.9 Loading and displaying the selected image.
//
// displayIcon
// Display the currently selected icon.
//
public void displayIcon(
Connection con)
{
// Get the proper list element
int n = getCategoryElement(currentList);
// Get the ID
String id = (String) iconDesc[n].get(item);
try {
// Create a Statement object
Statement stmt = con.createStatement();
89
ResultSet rs = stmt.executeQuery(
"SELECT ICON FROM ICONSTORE WHERE ID=" + id);
// If no rows are returned, the icon was not found
if (!rs.next()) {
stmt.close();
return;
}
if (inputStream == null) {
stmt.close();
return;
}
while (true) {
// Read from the input. The number of bytes read is returned.
bytes = inputStream.read(b);
if (bytes == -1) {
break;
}
90
currentFile = name;
}
catch (SQLException ex) {
Notice that each time an image is selected from the list, the image is read from the
database. It could be very costly in terms of memory resources to save all of the images,
so well just get the image from the database when needed. When the user selects an item
from the list, we can get the image description. This description is used to get the icon ID
from the image Hashtable. For the most part, we follow the same steps we have seen
several times before in getting results from a database. Unfortunately, weve had to use a
very nasty workaround here. The image is retrieved from the database as a binary
InputStream, and it is from this InputStream that we need to draw the image on our
canvas. This technique seems like it should be a simple matter, but it turns out to be
impossible as of the writing of this book. To get around this problem, the IconStore
application uses the InputStream to create a temporary file on disk, from which an
image can be loaded and drawn on the canvas. Hopefully, a method to draw images from
an InputStream will be part of Java in the future.
Figure 8.3 shows the IconStore screen after the user has selected an image from the initial
category list. Figure 8.4 shows the IconStore screen after the user has changed the
category (from the Icons menu) to sports and has made a selection.
91
Figure 8.4 Changing the image category.
Saving The Image
All thats left is to add the ability to save the image to disk. We saw previously how to
handle the Save As menu event, so we just need to be able to create the disk file. Our
workaround approach for drawing an image from an InputStream will be used to our
advantage. Because an image file has already been created, we can simply make a copy
of the temporary file. Listing 8.10 shows the code to copy a file.
Listing 8.10 Copying a file.
//
// copyFile
// Copy the source file to the target file.
//
public boolean copyFile(
String source,
String target)
{
boolean rc = false;
try {
FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(target);
int bytes;
byte b[] = new byte[1024];
// Read chunks from the input stream and write to the output
// stream.
while (true) {
bytes = in.read(b);
if (bytes == -1) {
break;
}
out.write(b, 0, bytes);
}
in.close();
out.close();
rc = true;
}
catch (java.lang.Exception ex) {
ex.printStackTrace();
}
return rc;
92
}
Figure 8.5 shows the IconStore screen after the user has selected the Save As menu
option.
Summary
Lets recap the important details that we have covered in this chapter:
Creating a basic GUI Java application
Opening a connection to a data source
Using database data to create dynamic GUI
components (menus and lists)
Handling user events
Handling JDBC InputStreams
93
Information is sent over networks in packets, and packet sniffing happens because a
computers network adapter is configured to read all of the packets that are sent over the
network, instead of just packets meant for that computer. Therefore, anyone with access
to a computer attached to your LAN can check out all transactions as they occur. Of
course, a well-managed network and users you can trust are the best methods of
preventing an inside job. Unfortunately, you must also consider another possibility: the
outside threat. The possibility that someone from outside your LAN might break into a
computer inside your LAN is another issue altogether; you must make sure that the other
computers on your LAN are properly secured. To prevent such a situation, a firewall is
often the best remedy. Though not completely foolproof, it does not allow indiscriminate
access to any computers that are behind the firewall from outside. There are several good
books on basic Internet security, and this books Website contains a list of URLs that
highlight several books on firewalls.
Packet sniffing doesnt necessarily involve only your local network; it can occur on the
route the packet takes from the remote client machine somewhere on the Internet to your
server machine. Along one of the many hops a packet takes as it travels across the
Internet, a hacker who has gained entry into one of these hop points could be monitoring
the packets sent to and from your server. Although this is a remote possibility, its still a
possibility. One solution is to limit the IP addresses from which connections to the
database server can be made. However, IP authorization isnt bulletproof eitherIP
spoofing is a workaround for this method. For more information on these basic security
issues, please see this books Web site for references to security material.
Web Server CGI Holes
If you only allow local direct access to your database server via pre-written software, like
CGI scripts run from Web pages, youll still find yourself with a possible security hole.
Some folks with too much time on their hands take great pleasure in hacking through
CGI scripts to seek out unauthorized information. Are you vulnerable to this type of
attack? Consider this situation: You have a CGI script that searches a table. The HTML
form that gives the CGI its search information uses a field containing a table name; if a
hacker realizes that you are directly patching in the table name from the HTML page, it
would be easy to modify the CGI parameters to point to a different table. Of course, the
easy solution to this scenario is to check in the CGI script that only the table you intend to
allow to be queried can be accessed.
For in-house distribution of Java programs that access database servers, many of these
security considerations are minimal. But for Internet applications, such as a
merchandising applet where a user enters a credit card number to purchase some goods,
you not only want to send this data encrypted to the Web server, but you want to protect
the actual database server that this sensitive data is stored on.
Finding A Solution
So how do we deal with these security holes? The most straightforward way is to use a
database server that implements secure login encryption. Some database servers do this
already, and with the proliferation of Web databases, login encryption is likely to be
94
incorporated into more popular database servers in the future. The other solution, which
is more viable, is to use an application server in a three-tier system. First, the Java
program uses encryption to send login information to the application server. Then, the
application server decodes the information. And finally, the application server sends the
decoded information to the database server, which is either running on the same machine
or on a machine attached to a secure local network. Well discuss application servers in
more detail in Chapter 11.
Another solution involves using the Java Security API, currently under development at
Javasoft. This API, which provides classes that perform encryption and authentication,
will be a standard part of the Java API and will allow you to use plug-in classes to
perform encryption on a remote connection.
As a user, how do you know if the Java applet youre getting is part of a front for an
illegitimate business? The Java Commerce API addresses the security issue of
determining whether an applet is from a legitimate source by using digital signatures,
authorization, and certification. Both the Java Commerce API and Java Security API will
likely be incorporated into Web browsers Java interpreters, and will also be linked in
heavily with the security features of the Web browser itself. At the time this manuscript
was written, however, these APIs were still under construction.
95
the user installs the applet locally and runs it, these security restrictions do not apply. But
unfortunately, that defeats the purpose behind an applet: a program that comes over the
network and begins running locally without installation.
Im A Certified Applet
To account for these tight security restrictions, the Java Commerce API addresses easing
security if the applet comes from a trusted source. This means that if the Web browser
recognizes as genuine the certification of the Web page, applets on the page may also be
considered certified. To obtain such a status, you must apply for certification from the
proper authority. When you receive certification, simply attach it to applets that are
served from your Web site. The Commerce and Security APIs allow for the fetching of
trusted applets, so if the user uses a Java interpreter that incorporates the Java Commerce
API and Security API, you (the developer) can serve applets that can connect to an
application server or database server running on a different machine than the Web server.
In fact, you can even attach to different database servers simultaneously if necessary. In
addition, this approach may allow the applet to save the contents of a database session on
the users disk, or read data from the users disk to load previous session data.
The exact security restrictions of trusted applets are not set in stone, and they may differ
depending on the Web browser the applet is run on. Also, the Java Commerce and
Security specifications and related APIs have not been finalized as of the writing of this
book, so much may change from the preliminary details of the security scheme by the
time the APIs are released and implemented.
Summary
Security in data transactions is a top priority in the Internet community. In this chapter,
weve discussed possible security holes and techniques to sew them up. We also took a
look at Javasofts approach to easing security restrictions for applets that come from a
certified trusted source.
In the next chapter, we jump back into the meat of the JDBC when we explore writing
JDBC drivers. Well explore the heart of the JDBCs implementation details, and well
also develop a real JDBC driver that can serve as the basis for drivers you write in the
future.
Chapter 10
Writing Database Drivers
Weve covered a lot of territory so far in this book. Now we can put some of your newly
gained knowledge to use. In this chapter, we will explore what it takes to develop a JDBC
driver. In doing so, we will also touch on some of the finer points of the JDBC
specification. Throughout this chapter, I will use excerpts from the SimpleText JDBC
driver that is included on the CD-ROM. This driver allows you to manipulate simple text
files; you will be able to create and drop files, as well as insert and select data within a
96
file. The SimpleText driver is not fully JDBC-compliant, but it provides a strong starting
point for developing a driver. Well cover what the JDBC components provide, how to
implement the JDBC API interfaces, how to write native code to bridge to an existing
non-Java API, some finer points of driver writing, and the major JDBC API interfaces
that must be implemented.
(column-element [, column-
element]...)
[(column-identifier [, column-
identifier]...)] VALUES
(insert-value [, insert-value]...)
dynamic-parameter ::= ?
97
select-list ::= * | column-identifier [, column-identifier]...
98
The DriverManager
The JDBC DriverManager is a static class that provides services to connect to JDBC
drivers. The DriverManager is provided by JavaSoft and does not require the driver
developer to perform any implementation. Its main purpose is to assist in loading and
initializing a requested JDBC driver. Other than using the DriverManager to register a
JDBC driver (registerDriver) to make itself known and to provide the logging facility
(which is covered in detail later), a driver does not interface with the DriverManager. In
fact, once a JDBC driver is loaded, the DriverManager drops out of the picture all
together, and the application or applet interfaces with the driver directly.
99
non-critical error (a warning or informational message). For this reason, JDBC treats
SQLWarnings much differently than SQLExceptions. SQLExceptions are thrown just
like any other type of exception; SQLWarnings are not thrown, but put on a list of
warnings on an owning object type (for instance, Connection, Statement, or ResultSet,
which well cover later). Because they are put on a list, it is up to the application to poll
for warnings after the completion of an operation. Listing 10.1 shows a method that
accepts an SQLWarning and places it on a list.
Listing 10.1 Placing an SQL Warning on a list.
//----------------------------------------------------------------------
----
// setWarning
// Sets the given SQLWarning in the warning chain. If null, the
// chain is reset. The local attribute lastWarning is used
// as the head of the chain.
//--------------------------------------------------------------- ------
---
protected void setWarning(
SQLWarning warning)
{
// Find the end of the chain. When the current warning does
// not have a next pointer, it must be the end of the chain.
while (chain.getNextWarning() != null) {
chain = chain.getNextWarning();
}
100
// First step should always be to clear the stack. If a warning
// is lingering, it will be discarded. It is up to the application
to
// check and clear the stack.
setWarning(null);
// Now, poll for the warning chain. We'll simply dump any warning
// messages to standard output.
SQLWarning chain = getWarnings();
if (chain != null) {
System.out.println("Warning(s):");
}
}
DataTruncation objects work in the same manner as SQLWarnings. A
DataTruncation object indicates that a data value that was being read or written was
truncated, resulting in a loss of data. The DataTruncation class has attributes that can be
set to specify the column or parameter number, whether a truncation occurred on a read
or a write, the size of the data that should have been transferred, and the number of bytes
that were actually transferred. We can modify our code from Listing 10.2 to include the
handling of DataTruncation objects, as shown in Listing 10.4.
Listing 10.4 Creating dDataTruncation warnings.
//----------------------------------------------------------------------
--
// fooBar
// Do nothing but put two SQLWarnings on our local
// warning stack (lastWarning) and a DataTruncation
// warning.
//----------------------------------------------------------------------
--
protected void fooBar()
{
101
// First step should always be to clear the stack. If a warning
// is lingering, it will be discarded. It is up to the application
to
// check and clear the stack.
setWarning(null);
// Now, poll for the warning chain. We'll simply dump any warning
// messages to standard output.
SQLWarning chain = getWarnings();
if (chain != null) {
System.out.println("Warning(s):");
102
a given database system, which is why data coercion becomes such a vital service (well
discuss data coercion a little later in this chapter). The data types are defined in
Types.class:
public class Types
{
103
JDBC as Numeric objects. The Numeric class is new with JDBC, and well be
discussing it shortly.
Binary Data: BINARY, VARBINARY, And LONGVARBINARY
The BINARY, VARBINARY, and LONGVARBINARY data types are used to express
binary (non-character) data. These data types are represented in JDBC as Java byte arrays.
Data of type BINARY is represented as a fixed-length byte array, and may include some
padding zeros to ensure that it is the proper length. If data is being written to a database,
the driver must ensure that the data is properly padded. Data of type VARBINARY is
represented as a variable-length byte array, and is trimmed to the actual length of the data.
LONGVARBINARY data can either be a variable-length byte array or returned by the
driver as a Java InputStream, allowing the data to be read in chunks of whatever size the
application desires.
Boolean Data: BIT
The BIT data type is used to represent a boolean valueeither true or falseand is
represented in JDBC as a Boolean object or boolean data type.
Integer Data: TINYINT, SMALLINT, INTEGER, And BIGINT
The TINYINT, SMALLINT, INTEGER, and BIGINT data types are used to represent
signed integer data. Data of type TINYINT is represented in JDBC as a Java byte data
type (1 byte), with a minimum value of -128 and a maximum value of 127. Data of type
SMALLINT is represented in JDBC as a Java short data type (2 bytes), with a minimum
value of -32,768 and a maximum value of 32,767. Data of type INTEGER is represented
as a Java int data type (4 bytes), with a minimum value of -2,147,483,648 and a
maximum value of 2,147,483,647. Data of type BIGINT is represented as a Java long
data type (8 bytes), with a minimum value of -9,223,372,036,854,775,808 and a
maximum value of 9,223,372,036,854,775,807.
Floating-Point Data: REAL, FLOAT, And DOUBLE
The REAL, FLOAT, and DOUBLE data types are used to represent signed,
approximate values. Data of type REAL supports seven digits of mantissa precision, and
is represented as a Java float data type. Data of types FLOAT and DOUBLE support 15
digits of mantissa precision, and are represented as Java double data types.
104
T i p: Be a w ar e of da t e l i mi t at i ons.
One imp or t ant note abo ut Dat e an d Time stamp obje ct s:
The J ava calend ar st ar t s at Janu ary 1, 1 970, which me ans
th at you ca nnot represen t da te s prior to 1970.
class NumericRoundingValueTest {
System.out.println("discounted price="+newPrice.toString());
105
// Perform the calculation to discount a price
public static Numeric discountItem(
Numeric price,
Numeric discount)
{
return price.subtract(price.multiply(discount));
}
}
Listing 10.6 produces the following output:
discounted price=004.17
discounted price with high rounding=004.18
Date
The Date class is used to represent dates in the ANSI SQL format YYYY-MM-DD,
where YYYY is a four-digit year, MM is a two-digit month, and DD is a two-digit day.
The JDBC Date class extends the existing java.util.Date class (setting the hour, minutes,
and seconds to zero) and, most importantly, adds two methods to convert Strings into
dates, and vice-versa:
// Create a Date object with a date of June 30th, 1996
Date d = Date.valueOf("1996-06-30");
106
The Time class is used to represent times in the ANSI SQL format HH:MM:SS, where
HH is a two-digit hour, MM is a two-digit minute, and SS is a two-digit second. The
JDBC Time class extends the existing java.util.Date class (setting the year, month, and
day to zero) and, most importantly, adds two methods to convert Strings into times, and
vice-versa:
// Create a Time object with a time of 2:30:08 pm
Time t = Time.valueOf("14:30:08");
Timestamp
The Timestamp class is used to represent a combination of date and time values in the
ANSI SQL format YYYY-MM-DD HH:MM:SS.F..., where YYYY is a four-digit year,
MM is a two-digit month, DD is a two-digit day, HH is a two-digit hour, MM is a two-
digit minute, SS is a two-digit second, and F is an optional fractional second up to nine
digits in length. The JDBC Timestamp class extends the existing java.util.Date class
(adding the fraction seconds) and, most importantly, adds two methods to convert Strings
into timestamps, and vice-versa:
// Create a Timestamp object with a date of 1996-06-30 and a time of
// 2:30:08 pm.
Timestamp t = Timestamp.valueOf("1996-06-30 14:30:08");
System.out.println("Timestamp=" + t.toString());
107
// Same thing, without leading zeros
Timestamp t2 = Timestamp.valueOf("1996-6-30 14:30:8");
System.out.println("Timestamp=" + t2.toString());
The Timestamp class also serves very well in validating timestamp values. If an invalid
time string is passed to the valueOf method, a java.lang.Illegal-ArgumentException is
thrown:
String s;
108
Listing 10.7 illustrates these suggestions. This module contains all of the native method
declarations, as well as the code to load our library. The library will be loaded when the
class is instantiated.
Listing 10.7 Java native methods.
//----------------------------------------------------------------------
--
// MyBridge.java
//
// Sample code to demonstrate the use of native methods
//----------------------------------------------------------------------
--
package jdbc.test;
import java.sql.*;
109
Once this module has been compiled (javac), a Java generated header file and C file must
be created:
javah jdbc.test.MyBridge
javah -stubs jdbc.test.MyBridge
These files provide the mechanism for the Java and C worlds to communicate with each
other. Listing 10.8 shows the generated header file (jdbc_test_MyBridge.h, in this case),
which will be included in our C bridge code.
Listing 10.8 Machine-generated header file for native methods.
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <native.h>
/* Header for class jdbc_test_MyBridge */
#ifndef _Included_jdbc_test_MyBridge
#define _Included_jdbc_test_MyBridge
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) long jdbc_test_MyBridge_getINTSize(struct
Hjdbc_test_MyBridge *);
__declspec(dllexport) long jdbc_test_MyBridge_getINTValue(struct
Hjdbc_test_MyBridge *,HArrayOfByte *);
struct Hjava_lang_String;
__declspec(dllexport) void jdbc_test_MyBridge_callSomeFunction(struct
Hjdbc_test_MyBridge *,struct Hjava_lang_String *,HArrayOfByte *);
#ifdef __cplusplus
}
#endif
#endif
The generated C file (shown in Listing 10.9) must be compiled and linked with the bridge.
110
return _P_ + 1;
}
/* SYMBOL: "jdbc/test/MyBridge/getINTValue([B)I",
Java_jdbc_test_MyBridge_getINTValue_stub */
__declspec(dllexport) stack_item
*Java_jdbc_test_MyBridge_getINTValue_stub(stack_item *_P_,struct
execenv *_EE_) {
extern long jdbc_test_MyBridge_getINTValue(void *,void *);
_P_[0].i = jdbc_test_MyBridge_getINTValue(_P_[0].p,((_P_[1].p)));
return _P_ + 1;
}
/* SYMBOL: "jdbc/test/MyBridge/callSomeFunction(Ljava/lang/String;[B)V",
Java_jdbc_test_MyBridge_callSomeFunction_stub */
__declspec(dllexport) stack_item
*Java_jdbc_test_MyBridge_callSomeFunction_stub(stack_item *_P_,struct
execenv *_EE_) {
extern void jdbc_test_MyBridge_callSomeFunction(void *,void
*,void
*);
(void)
jdbc_test_MyBridge_callSomeFunction(_P_[0].p,((_P_[1].p)),
((_P_[2].p)));return _P_;
}
The bridge code is shown in Listing 10.10. The function prototypes were taken from the
generated header file.
Listing 10.10 Bridge code.
//----------------------------------------------------------------------
--
// MyBridge.c
//
// Sample code to demonstrate the use of native methods
//----------------------------------------------------------------------
--
#include <stdio.h>
#include <ctype.h>
#include <string.h>
//----------------------------------------------------------------------
--
// getINTSize
// Return the size of an int
//----------------------------------------------------------------------
--
long jdbc_test_MyBridge_getINTSize(
struct Hjdbc_test_MyBridge *caller)
{
return sizeof(int);
111
}
//----------------------------------------------------------------------
--
// getINTValue
// Given a buffer, return the value as an int
//----------------------------------------------------------------------
--
long jdbc_test_MyBridge_getINTValue(
struct Hjdbc_test_MyBridge *caller,
HArrayOfByte *buf)
{
// Cast our array of bytes to an integer pointer
int* pInt = (int*) unhand (buf)->body;
//----------------------------------------------------------------------
--
// callSomeFunction
// Call some function that takes a String and an int pointer as
arguments
//----------------------------------------------------------------------
--
void jdbc_test_MyBridge_callSomeFunction(
struct Hjdbc_test_MyBridge *caller,
struct Hjava_lang_String *stringValue,
HArrayOfByte *buf)
{
// This fictitious function will print the string, then return the
// length of the string in the int pointer.
printf("String value=%s\n", pString);
*pInt = strlen(pString);
}
Now, create a library (DLL or Shared Object) by compiling this module and linking it
with the jdbc_test_MyDriver compiled object and the one required Java library, javai.lib.
Heres the command line I used to build it for Win95/NT:
cl -DWIN32 mybridge.c jdbc_test_mybridge.c -FeMyBridge.dll -MD -LD
javai.lib
Now we can use our native bridge, as shown in Listing 10.11.
Listing 10.11 Implementing the bridge.
import jdbc.test.*;
import java.sql.*;
112
class Test {
try {
Implementing Interfaces
The JDBC API specification provides a series of interfaces that must be implemented by
the JDBC driver developer. An interface declaration creates a new reference type
consisting of constants and abstract methods. An interface cannot contain any
implementations (that is, executable code). What does all of this mean? The JDBC API
specification dictates the methods and method interfaces for the API, and a driver must
fully implement these interfaces. A JDBC application makes method calls to the JDBC
113
interface, not a specific driver. Because all JDBC drivers must implement the same
interface, they are interchangeable.
There are a few rules that you must follow when implementing interfaces. First, you must
implement the interface exactly as specified. This includes the name, return value,
parameters, and throws clause. Secondly, you must be sure to implement all interfaces as
public methods. Remember, this is the interface that other classes will see; if it isnt
public, it cant be seen. Finally, all methods in the interface must be implemented. If you
forget, the Java compiler will kindly remind you.
Take a look at Listing 10.12 for an example of how interfaces are used. The code defines
an interface, implements the interface, and then uses the interface.
package jdbc.test;
114
public int method2(int x)
{
return addOne(x);
}
class TestInterface {
}
}
As you can see, implementing interfaces is easy. Well go into more detail with the major
JDBC interfaces later in this chapter. But first, we need to cover some basic foundations
that should be a part of every good JDBC driver.
Tracing
One detail that is often overlooked by software developers is providing a facility to
enable debugging. The JDBC API does provide methods to enable and disable tracing,
but it is ultimately up to the driver developer to provide tracing information in the driver.
115
It becomes even more critical to provide a detailed level of tracing when you consider the
possible wide-spread distribution of your driver. People from all over the world may be
using your software, and they will expect a certain level of support if problems arise. For
this reason, I consider it a must to trace all of the JDBC API method calls (so that a
problem can be re-created using the output from a trace).
Turning On Tracing
The DriverManager provides a method to set the tracing PrintStream to be used for all
of the drivers; not only those that are currently active, but any drivers that are
subsequently loaded. Note that if two applications are using JDBC, and both have turned
tracing on, the PrintStream that is set last will be shared by both applications. The
following code snippet shows how to turn tracing on, sending any trace messages to a
local file:
try {
// Create a new OuputStream using a file. This may fail if the
// calling application/applet does not have the proper security
// to write to a local disk.
java.io.OutputStream outFile = new
java.io.FileOutputStream("jdbc.out");
116
DriverManager.println("Trace=" + a + b + c);
In this example, a String message of Trace=The quick brown fox jumped over the lazy
dog will be constructed, the message will be provided as a parameter to the
DriverManager.println method, and the message will be written to the OutputStream
being used for tracing (if one has been registered).
Some of the JDBC components are also nice enough to provide tracing information. The
DriverManager object traces most of its method calls. SQLException also sends trace
information whenever an exception is thrown. If you were to use the previous code
example and enable tracing to a file, the following example output will be created when
attempting to connect to the SimpleText driver:
DriverManager.initialize: jdbc.drivers = null
JDBC DriverManager initialized
registerDriver:
driver[className=jdbc.SimpleText.SimpleTextDriver,context=null,
jdbc.SimpleText.SimpleTextDriver@1393860]
DriverManager.getConnection("jdbc:SimpleText")
trying
driver[className=jdbc.SimpleText.SimpleTextDriver,context=null,
jdbc.SimpleText.SimpleTextDriver@1393860]
driver[className=jdbc.SimpleText.SimpleTextDriver,context=null,j
dbc.SimpleText.SimpleTextDriver@1393860]
}
From an application, you can use this method to check if tracing has been previously
enabled before blindly setting it:
// Before setting tracing on, check to make sure that tracing is not
// already turned on. If it is, notify the application.
if (traceOn()) {
// Issue a warning that tracing is already enabled
.
117
.
.
}
From the driver, I use this method to check for tracing before attempting to send
information to the PrintStream. In the example where we traced the message text of
Trace=The quick brown fox jumped over the lazy dog, a lot had to happen before the
message was sent to the DriverManager.println method. All of the given String objects
had to be concatenated, and a new String had to be constructed. Thats a lot of overhead
to go through before even making the println call, especially if tracing is not enabled
(which will probably be the majority of the time). So, for performance reasons, I prefer to
ensure that tracing has been enabled before assembling my trace message:
// Send some information to the JDBC trace OutputStream
String a = "The quick brown fox ";
String b = "jumped over the ";
String c = "lazy dog";
Data Coercion
At the heart of every JDBC driver is data. That is the whole purpose of the driver:
providing data. Not only providing it, but providing it in a requested format. This is what
data coercion is all aboutconverting data from one format to another. As Figure 10.1
shows, JDBC specifies the necessary conversions.
import java.sql.*;
118
extends Object
{
//------------------------------------------------------------------
------
// Constructors
//----------------------------------------------------------------------
--
public CommonValue()
{
data = null;
}
public CommonValue(String s)
{
data = (Object) s;
internalType = Types.VARCHAR;
}
public CommonValue(int i)
{
data = (Object) new Integer(i);
internalType = Types.INTEGER;
}
public CommonValue(Integer i)
{
data = (Object) i;
internalType = Types.INTEGER;
}
//----------------------------------------------------------------------
-
// isNull
// returns true if the value is null
//----------------------------------------------------------------------
--
public boolean isNull()
{
return (data == null);
}
//------------------------------------------------------------------
------
// getMethods
//----------------------------------------------------------------------
--
119
String s;
switch(internalType) {
case Types.VARCHAR:
s = (String) data;
break;
case Types.INTEGER:
s = ((Integer) data).toString();
break;
case Types.VARBINARY:
{
// Convert a byte array into a String of hex digits
byte b[] = (byte[]) data;
int len = b.length;
String digits = "0123456789ABCDEF";
char c[] = new char[len * 2];
default:
throw new SQLException("Unable to convert data type to
String: " +
internalType);
}
return s;
}
switch(internalType) {
case Types.VARCHAR:
i = (Integer.valueOf((String) data)).intValue();
120
break;
case Types.INTEGER:
i = ((Integer) data).intValue();
break;
default:
throw new SQLException("Unable to convert data type to
String: " +
internalType);
}
return i;
}
switch(internalType) {
case Types.VARCHAR:
{
if ((len % 2) != 0) {
throw new SQLException(
"Data must have an even number of hex
digits");
}
if (index < 0) {
throw new SQLException("Invalid hex digit");
}
if (index < 0) {
121
throw new SQLException("Invalid hex digit");
}
b[i] += (byte) index;
}
}
break;
case Types.VARBINARY:
b = (byte[]) data;
break;
default:
throw new SQLException("Unable to convert data type to
byte[]: " +
internalType);
}
return b;
}
Note that the SimpleText driver supports only character, integer, and binary data; thus,
CommonValue only accepts these data types, and only attempts to convert data to these
same types. A more robust driver would need to further implement this class to include
more (if not all) data types.
Escape Clauses
Another consideration when implementing a JDBC driver is processing escape clauses.
Escape clauses are used as extensions to SQL and provide a method to perform DBMS-
specific extensions, which are interoperable among DBMSes. The JDBC driver must
accept escape clauses and expand them into the native DBMS format before processing
the SQL statement. While this sounds simple enough on the surface, this process may
turn out to be an enormous task. If you are developing a driver that uses an existing
DBMS, and the JDBC driver simply passes SQL statements to the DBMS, you may have
to develop a parser to scan for escape clauses.
The following types of SQL extensions are defined:
Date, time, and timestamp data
Scalar functions such as numeric, string, and data
type conversion
LIKE predicate escape characters
Outer joins
Procedures
The JDBC specification does not directly address escape clauses; they are inherited from
the ODBC specification. The syntax defined by ODBC uses the escape clause provided
122
by the X/OPEN and SQL Access Group SQL CAE specification (1992). The general
syntax for an escape clause is:
{escape}
Well cover the specific syntax for each type of escape clause in the following sections.
Date, Time, And Timestamp
The date, time, and timestamp escape clauses allow an application to specify date, time,
and timestamp data in a uniform manner, without concern to the native DBMS format
(for which the JDBC driver is responsible). The syntax for each (respectively) is
{d 'value'}
{t 'value'}
{ts 'value'}
where d indicates value is a date in the format yyyy-mm-dd, t indicates value is a time in
the format hh:mm:ss, and ts indicates value is a timestamp in the format yyyy-mm-dd
hh:mm:ss[.f...]. The following SQL statements illustrate the use of each:
UPDATE EMPLOYEE SET HIREDATE={d '1992-04-01'}
UPDATE EMPLOYEE SET LAST_IN={ts '1996-07-03 08:00:00'}
UPDATE EMPLOYEE SET BREAK_DUE={t '10:00:00'}
Scalar Functions
The five types of scalar functionsstring, numeric, time and date, system, and data type
conversionall use the syntax:
{fn scalar-function}
To determine what type of string functions a JDBC driver supports, an application can
use the DatabaseMetaData method getStringFunctions. This method returns a comma-
separated list of string functions, possibly containing ASCII, CHAR, CONCAT,
DIFFERENCE, INSERT, LCASE, LEFT, LENGTH, LOCATE, LTRIM, REPEAT,
REPLACE, RIGHT, RTRIM, SOUNDEX, SPACE, SUBSTRING, and/or UCASE.
To determine what type of numeric functions a JDBC driver supports, an application can
use the DatabaseMetaData method getNumericFunctions. This method returns a
comma-separated list of numeric functions, possibly containing ABS, ACOS, ASIN,
ATAN, ATAN2, CEILING, COS, COT, DEGREES, EXP, FLOOR, LOG, LOG10,
MOD, PI, POWER, RADIANS, RAND, ROUND, SIGN, SIN, SQRT, TAN, and/or
TRUNCATE.
To determine what type of system functions a JDBC driver supports, an application can
use the DatabaseMetaData method getSystemFunctions. This method returns a
comma-separated list of system functions, possibly containing DATABASE, IFNULL,
and/or USER.
To determine what type of time and date functions a JDBC driver supports, an
application can use the DatabaseMetaData method getTimeDateFunctions. This
method returns a comma-separated list of time and date functions, possibly containing
CURDATE, CURTIME, DAYNAME, DAYOFMONTH, DAYOFWEEK,
123
DAYOFYEAR, HOUR, MINUTE, MONTH, MONTHNAME, NOW, QUARTER,
SECOND, TIMESTAMPADD, TIMESTAMPDIFF, WEEK, and/or YEAR.
To determine what type of explicit data type conversions a JDBC driver supports, an
application can use the DatabaseMetaData method supportsConvert. This method has
two parameters: a from SQL data type and a to SQL data type. If the explicit data
conversion between the two SQL types is supported, the method returns true. The syntax
for the CONVERT function is
{fn CONVERT(value, data_type)}
where value is a column name, the result of another scalar function, or a literal, and
data_type is one of the JDBC SQL types listed in the Types class.
LIKE Predicate Escape Characters
In a LIKE predicate, the % (percent character) matches zero or more of any character,
and the _ (underscore character) matches any one character. In some instances, an SQL
query may have the need to search for one of these special matching characters. In such
cases, you can use the % and _ characters as literals in a LIKE predicate by
preceding them with an escape character. The DatabaseMetaData method getSearch-
StringEscape returns the default escape character (which for most DBMSes will be the
backslash character \). To override the escape character, use the following syntax:
{escape 'escape-character'}
The following SQL statement uses the LIKE predicate escape clause to search for any
columns that start with the % character:
SELECT * FROM EMPLOYEE WHERE NAME LIKE '\%' {escape '\'}
Outer Joins
JDBC supports the ANSI SQL-92 LEFT OUTER JOIN syntax. The escape clause syntax
is
{oj outer-join}
where outer-join is the table-reference LEFT OUTER JOIN {table-reference | outer-join}
ON search-condition.
Procedures
A JDBC application can call a procedure in place of an SQL statement. The escape clause
used for calling a procedure is
{[?=] call procedure-name[(param[, param]...)]}
where procedure-name specifies the name of a procedure stored on the data source, and
param specifies procedure parameters. A procedure can have zero or more parameters,
and may return a value.
124
SimpleText project whenever applicable. You should understand the JDBC API
specification before attempting to create a JDBC driver; this section is meant to enhance
the specification, not to replace it.
Driver
The Driver class is the entry point for all JDBC drivers. From here, a connection to the
database can be made in order to perform work. This class is intentionally very small; the
intent is that JDBC drivers can be pre-registered with the system, enabling the
DriverManager to select an appropriate driver given only a URL (Universal Resource
Locator). The only way to determine which driver can service the given URL is to load
the Driver class and let each driver respond via the acceptsURL method. To keep the
amount of time required to find an appropriate driver to a minimum, each Driver class
should be as small as possible so it can be loaded quickly.
Register Thyself
The very first thing that a driver should do is register itself with the DriverManager. The
reason is simple: You need to tell the DriverManager that you exist; otherwise you may
not be loaded. The following code illustrates one way of loading a JDBC driver:
java.sql.Driver d = (java.sql.Driver)
Class.forName
("jdbc.SimpleText.SimpleTextDriver").newInstance();
125
URL Processing
As I mentioned a moment ago, the acceptsURL method informs the DriverManager
whether a given URL is supported by the driver. The general format for a JDBC URL is
jdbc:subprotocol:subname
where subprotocol is the particular database connectivity mechanism supported (note that
this mechanism may be supported by multiple drivers) and the subname is defined by the
JDBC driver. For example, the format for the JDBC-ODBC Bridge URL is:
jdbc:odbc:data source name
Thus, if an application requests a JDBC driver to service the URL of
jdbc:odbc:foobar
the only driver that will respond that the URL is supported is the JDBC-ODBC Bridge;
all others will ignore the request.
Listing 10.14 shows the acceptsURL method for the SimpleText driver. The SimpleText
driver will accept the following URL syntax:
jdbc:SimpleText
Note that no subname is required; if a subname is provided, it will be ignored.
Listing 10.14 The acceptsURL method.
//----------------------------------------------------------------------
--
// acceptsURL - JDBC API
//
// Returns true if the driver thinks that it can open a connection
// to the given URL. Typically, drivers will return true if they
// understand the subprotocol specified in the URL, and false if
// they don't.
//
// url The URL of the database.
//
// Returns true if this driver can connect to the given URL.
//----------------------------------------------------------------------
--
public boolean acceptsURL(
String url)
throws SQLException
{
if (traceOn()) {
trace("@acceptsURL (url=" + url + ")");
}
boolean rc = false;
// Get the subname from the url. If the url is not valid for
// this driver, a null will be returned.
if (getSubname(url) != null) {
rc = true;
}
if (traceOn()) {
126
trace(" " + rc);
}
return rc;
}
//----------------------------------------------------------------------
--
// getSubname
// Given a URL, return the subname. Returns null if the protocol is
// not "jdbc" or the subprotocol is not "simpletext."
//----------------------------------------------------------------------
--
public String getSubname(
String url)
{
String subname = null;
String protocol = "JDBC";
String subProtocol = "SIMPLETEXT";
Driver Properties
127
Connecting to a JDBC driver with only a URL specification is great, but the vast majority
of the time, a driver will require additional information in order to properly connect to a
database. The JDBC specification has addressed this issue with the getPropertyInfo
method. Once a Driver has been instantiated, an application can use this method to find
out what required and optional properties can be used to connect to the database. You
may be tempted to require the application to embed properties within the URL subname,
but by returning them from the getPropertyInfo method, you can identify the properties
at runtime, giving a much more robust solution. Listing 10.15 shows an application that
loads the SimpleText driver and gets the property information.
class PropertyTest {
128
}
}
catch (SQLException ex) {
System.out.println ("\nSQLException(s) caught\n");
Property 1
Name: Directory
Description: Initial text file directory
Required: false
Value: null
Choices: null
It doesnt take a lot of imagination to envision an application or applet that gathers the
property information and prompts the user in order to connect to the database. The actual
code to implement the getPropertyInfo method for the SimpleText driver is very simple,
as shown in Listing 10.16.
Listing 10.16 Implementing the getPropertyInfo method.
//----------------------------------------------------------------------
--
// getPropertyInfo - JDBC API
//
// The getPropertyInfo method is intended to allow a generic GUI tool to
// discover what properties it should prompt a human for in order to get
// enough information to connect to a database. Note that depending on
// the values the human has supplied so far, additional values may
become
// necessary, so it may be necessary to iterate though several calls.
// to getPropertyInfo.
//
// url The URL of the database to connect to.
//
// info A proposed list of tag/value pairs that will be sent on
// connect open.
//
// Returns an array of DriverPropertyInfo objects describing possible
// properties. This array may be an empty array if no
// properties are required.
//----------------------------------------------------------------------
--
129
public DriverPropertyInfo[] getPropertyInfo(
String url,
java.util.Properties info)
throws SQLException
{
DriverPropertyInfo prop[];
// Only one property required for the SimpleText driver, the
// directory. Check the property list coming in. If the
// directory is specified, return an empty list.
if (info.getProperty("Directory") == null) {
}
else {
// Create an empty list
prop = new DriverPropertyInfo[0];
}
return prop;
130
// string tag/value pairs as connection arguments.
// Normally, at least "user" and "password" properties should be
// included in the Properties.
//
// url The URL of the database to connect to.
//
// info a list of arbitrary string tag/value pairs as
// connection arguments; normally, at least a "user" and
// "password" property should be included.
//
// Returns a Connection to the URL.
//----------------------------------------------------------------------
--
public Connection connect(
String url,
java.util.Properties info)
throws SQLException
{
if (traceOn()) {
trace("@connect (url=" + url + ")");
}
return con;
}
As you can see, there isnt a lot going on here for the SimpleText driver; remember that
we need to keep the size of the Driver class implementation as small as possible. To aid
in this, all of the code required to perform the database connection resides in the
Connection class, which well discuss next.
Connection
The Connection class represents a session with the data source. From here, you can
create Statement objects to execute SQL statements and gather database statistics.
131
Depending upon the database that you are using, multiple connections may be allowed
for each driver.
For the SimpleText driver, we dont need to do anything more than actually connect to
the database. In fact, there really isnt a database at alljust a bunch of text files. For
typical database drivers, some type of connection context will be established, and default
information will be set and gathered. During the SimpleText connection initialization, all
that we need to do is check for a read-only condition (which can only occur within
untrusted applets) and any properties that are supplied by the application, as shown in
Listing 10.18.
Listing 10.18 SimpleText connection initialization.
public void initialize(
Driver driver,
java.util.Properties info)
throws SQLException
{
// Save the owning driver object
ownerDriver = driver;
if (securityManager != null) {
try {
// Use some arbitrary file to check for file write
privileges
securityManager.checkWrite ("SimpleText_Foo");
// Flag is set if no exception is thrown
canWrite = true;
}
if (s == null) {
s = System.getProperty("user.dir");
132
}
setCatalog(s);
Creating Statements
From the Connection object, an application can create three types of Statement objects.
The base Statement object is used for executing SQL statements directly. The
PreparedStatement object (which extends Statement) is used for pre-compiling SQL
statements that may contain input parameters. The CallableStatement object (which
extends PreparedStatement) is used to execute stored procedures that may contain both
input and output parameters.
For the SimpleText driver, the createStatement method does nothing more than create a
new Statement object. For most database systems, some type of statement context, or
handle, will be created. One thing to note whenever an object is created in a JDBC driver:
Save a reference to the owning object because you will need to obtain information (such
as the connection context from within a Statement object) from the owning object.
Consider the createStatement method within the Connection class:
public Statement createStatement()
throws SQLException
{
if (traceOn()) {
trace("Creating new SimpleTextStatement");
return stmt;
}
Now consider the corresponding initialize method in the Statement class:
public void initialize(
SimpleTextConnection con)
throws SQLException
{
// Save the owning connection object
ownerConnection = con;
}
Which module will you compile first? You cant compile the Connection class until the
Statement class has been compiled, and you cant compile the Statement class until the
Connection class has been compiled. This is a circular dependency. Of course, the Java
compiler does allow multiple files to be compiled at once, but some build environments
do not support circular dependency. I have solved this problem in the SimpleText driver
133
by defining some simple interface classes. In this way, the Statement class knows only
about the general interface of the Connection class; the implementation of the interface
does not need to be present. Our modified initialize method looks like this:
public void initialize(
SimpleTextIConnection con)
throws SQLException
{
// Save the owning connection object
ownerConnection = con;
}
Note that the only difference is the introduction of a new class, SimpleTextIConnection,
which replaces SimpleTextConnection. I have chosen to preface the JDBC class name
with an I to signify an interface. Heres the interface class:
public interface SimpleTextIConnection
extends java.sql.Connection
{
String[] parseSQL(String sql);
Hashtable getTables(String directory, String table);
Hashtable getColumns(String directory, String table);
String getDirectory(String directory);
}
Note that our interface class extends the JDBC class, and our Connection class
implements this new interface. This allows us to compile the interface first, then the
Statement, followed by the Connection. Say good-bye to your circular dependency
woes.
Now, back to the Statement objects. The prepareStatement and prepareCall methods
of the Connection object both require an SQL statement to be provided. This SQL
statement should be pre-compiled and stored with the Statement object. If any errors are
present in the SQL statement, an exception should be raised, and the Statement object
should not be created.
DatabaseMetaData
At over 130 methods, the DatabaseMetaData class is by far the largest. It supplies
information about what is supported and how things are supported. It also supplies
catalog information such as listing tables, columns, indexes, procedures, and so on.
Because the JDBC API specification does an adequate job of explaining the methods
contained in this class, and most of them are quite straightforward, well just take a look
134
at how the SimpleText driver implements the getTables catalog method. But first, lets
review the basic steps needed to implement each of the catalog methods (that is, those
methods that return a ResultSet):
1. Create the result columns, which includes the
column name, type, and other information about each
of the columns. You should perform this step regardless
of whether the database supports a given catalog
function (such as stored procedures). I believe that it is
much better to return an empty result set with only the
column information than to raise an exception
indicating that the database does not support the
function. The JDBC specification does not currently
address this issue, so it is open for interpretation.
2. Retrieve the catalog information from the database.
3. Perform any filtering necessary. The application
may have specified the return of only a subset of the
catalog information. You may need to filter the
information in the JDBC driver if the database system
doesnt.
4. Sort the result data per the JDBC API specification.
If you are lucky, the database you are using will sort
the data in the proper sequence. Most likely, it will not.
In this case, you will need to ensure that the data is
returned in the proper order.
5. Return a ResultSet containing the requested
information.
The SimpleText getTables method will return a list of all of the text files in the catalog
(directory) given. If no catalog is supplied, the default directory is used. Note that the
SimpleText driver does not perform all of the steps shown previously; it does not provide
any filtering, nor does it sort the data in the proper sequence. You are more than welcome
to add this functionality. In fact, I encourage it. One note about column information: I
prefer to use a Hashtable containing the column number as the key, and a class
containing all of the information about the column as the data value. So, for all
ResultSets that are generated, I create a Hashtable of column information that is then
used by the ResultSet object and the ResultSetMetaData object to describe each column.
Listing 10.19 shows the SimpleTextColumn class that is used to hold this information
for each column.
Listing 10.19 The SimpleTextColumn class.
package jdbc.SimpleText;
135
// Constructor
//----------------------------------------------------------------------
--
public SimpleTextColumn(
String name,
int type,
int precision)
{
this.name = name;
this.type = type;
this.precision = precision;
}
public SimpleTextColumn(
String name,
int type)
{
this.name = name;
this.type = type;
this.precision = 0;
}
public SimpleTextColumn(
String name)
{
this.name = name;
this.type = 0;
this.precision = 0;
}
136
// (3) TABLE_NAME String => table name
// (4) TABLE_TYPE String => table type
// Typical types are "TABLE", "VIEW", "SYSTEM TABLE",
// "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM"
// (5) REMARKS String => explanatory comment on the table
//
// Note: Some databases may not return information for
// all tables.
//
// catalog a catalog name; "" retrieves those without a
// catalog.
// schemaPattern a schema name pattern; "" retrieves those
// without a schema.
// tableNamePattern a table name pattern.
// types a list of table types to include; null returns
all
// types.
//
// Returns a ResultSet. Each row is a table description.
//----------------------------------------------------------------------
public ResultSet getTables(
String catalog,
String schemaPattern,
String tableNamePattern,
String types[])
throws SQLException
{
if (traceOn()) {
trace("@getTables(" + catalog + ", " + schemaPattern +
", " + tableNamePattern + ")");
}
if (types != null) {
willBeEmpty = true;
for (int ii = 0; ii < types.length; ii++) {
137
if (types[ii].equalsIgnoreCase("TABLE")) {
willBeEmpty = false;
break;
}
}
}
if (!willBeEmpty) {
// Get a Hashtable with all tables
Hashtable tables = ownerConnection.getTables(
ownerConnection.getDirectory(catalog),
tableNamePattern);
Hashtable singleRow;
SimpleTextTable table;
return rs;
}
Lets take a closer look at whats going on here. The first thing we do is create a
Statement object to fake out the ResultSet object that we will be creating to return
back to the application. The ResultSet object is dependent upon a Statement object, so
well give it one. The next thing we do is create all of the column information. Note that
all of the required columns are given in the JDBC API specification. The add method
simply adds a SimpleTextColumn object to the Hashtable of columns:
protected void add(
Hashtable h,
int col,
String name,
int type)
{
h.put(new Integer(col), new SimpleTextColumn(name,type));
138
}
Next, we create another Hashtable to hold all of the data for all of the catalog rows. The
Hashtable contains an entry for each row of data. The entry contains the key, which is
the row number, and the data value, which is yet another Hashtable whose key is the
column number and whose data value is a CommonValue object containing the actual
data. Remember that the CommonValue class provides us with the mechanism to store
data and coerce it as requested by the application. If a column is null, we simply cannot
store any information in the Hashtable for that column number.
After some sanity checking to ensure that we really need to look for the catalog
information, we get a list of all of the tables. The getTables method in the Connection
class provides us with a list of all of the SimpleText data files:
public Hashtable getTables(
String dir,
String table)
{
Hashtable list = new Hashtable();
if (file.isDirectory()) {
}
}
return list;
}
Again, I use a Hashtable for each table (or file in our case) that is found. By now, you
will have realized that I really like using Hashtables; they can grow in size dynamically
and provide quick access to data. And because a Hashtable stores data as an abstract
Object, I can store whatever is necessary. In this case, each Hashtable entry for a table
contains a SimpleTextTable object:
public class SimpleTextTable
139
extends Object
{
//----------------------------------------------------------------------
--
// Constructor
//----------------------------------------------------------------------
--
public SimpleTextTable(
String dir,
String file)
{
this.dir = dir;
this.file = file;
140
//----------------------------------------------------------------------
--
// executeQuery - JDBC API
// Execute an SQL statement that returns a single ResultSet.
//
// sql Typically this is a static SQL SELECT statement.
//
// Returns the table of data produced by the SQL statement.
//----------------------------------------------------------------------
--
public ResultSet executeQuery(
String sql)
throws SQLException
{
if (traceOn()) {
trace("@executeQuery(" + sql + ")");
}
java.sql.ResultSet rs = null;
//----------------------------------------------------------------------
--
// executeUpdate - JDBC API
// Execute an SQL INSERT, UPDATE, or DELETE statement. In addition,
// SQL statements that return nothing, such as SQL DDL statements,
// can be executed.
//
// sql an SQL INSERT, UPDATE, or DELETE statement, or an SQL
// statement that returns nothing.
//
// Returns either the row count for INSERT, UPDATE, or DELETE; or 0
// for SQL statements that return nothing.
//----------------------------------------------------------------------
--
public int executeUpdate(
String sql)
throws SQLException
{
if (traceOn()) {
trace("@executeUpdate(" + sql + ")");
}
int count = -1;
141
// Execute the query. If execute returns false, then an update
// count exists.
if (execute(sql) == false) {
count = getUpdateCount();
}
else {
// If the statement does not create an update count, the
// specification indicates that an SQLException should be
raised.
throw new SQLException("Statement did not create an update
count");
}
return count;
}
As you can see, executeQuery and executeUpdate are simply helper methods for an
application; they are built completely upon other methods contained within the class. The
execute method accepts an SQL statement as its only parameter, and will be implemented
differently, depending upon the underlying database system. For the SimpleText driver,
the SQL statement will be parsed, prepared, and executed. Note that parameter markers
are not allowed when executing an SQL statement directly. If the SQL statement created
results containing columnar data, execute will return true; if the statement created a count
of rows affected, execute will return false. If execute returns true, the application then
uses getResultSet to return the current result information; otherwise, getUpdateCount
will return the number of rows affected.
Warnings
As opposed to SQLException, which indicates a critical error, an SQLWarning can be
issued to provide additional information to the application. Even though SQLWarning is
derived from SQLException, warnings are not thrown. Instead, if a warning is issued, it
is placed on a warning stack with the Statement object (the same holds true for the
Connection and ResultSet objects). The application must then check for warnings after
every operation using the getWarnings method. At first, this may seem a bit
cumbersome, but when you consider the alternative of wrapping try...catch statements
around each operation, this seems like a better solution. Note also that warnings can be
chained together, just like SQLExceptions (for more information on chaining, see the
JDBC Exception Types section earlier in this chapter).
142
false, you have either reached the end of the results, or an update count exists; you must
call getUpdateCount to determine which situation exists. If getUpdateCount returns -1,
you have reached the end of the results; otherwise, it will return the number of rows
affected by the statement.
The SimpleText driver does not support multiple result sets, so I dont have any example
code to present to you. The only DBMS that I am aware of that supports this is Sybase.
Because there are already multiple JDBC drivers available for Sybase (one of which I
have developed), I doubt you will have to be concerned with getMoreResults. Consider
yourself lucky.
PreparedStatement
The PreparedStatement is used for pre-compiling an SQL statement, typically in
conjunction with parameters, and can be efficiently executed multiple times with just a
change in a parameter value; the SQL statement does not have to be parsed and compiled
each time. Because the PreparedStatement class extends the Statement class, you will
have already implemented a majority of the methods. The executeQuery,
executeUpdate, and execute methods are very similar to the Statement methods of the
same name, but they do not take an SQL statement as a parameter. The SQL statement
for the PreparedStatement was provided when the object was created with the
prepareStatement method from the Connection object. One danger to note here:
Because PreparedStatement is derived from the Statement class, all of the methods in
Statement are also in PreparedStatement. The three execute methods from the
Statement class that accept SQL statements are not valid for the PreparedStatement
class. To prevent an application from invoking these methods, the driver should also
implement them in PreparedStatement, as shown here:
// The overloaded executeQuery on the Statement object (which we
// extend) is not valid for PreparedStatement or CallableStatement
// objects.
public ResultSet executeQuery(
String sql)
throws SQLException
{
throw new SQLException("Method is not valid");
}
143
String sql)
throws SQLException
{
throw new SQLException("Method is not valid");
}
clearWarnings();
144
Because the CommonValue class does not yet support all of the JDBC data types, not all
of the set methods have been implemented in the SimpleText driver. You can see,
however, how easy it would be to fully implement these methods once CommonValue
supported all of the necessary data coercion.
What Is It?
Another way to set parameter values is by using the setObject method. This method can
easily be built upon the other set methods. Of interest here is the ability to set an Object
without giving the JDBC driver the type of driver being set. The SimpleText driver
implements a simple method to determine the type of object, given only the object itself:
protected int getObjectType(
Object x)
throws SQLException
{
try {
if ((Integer) x != null) {
return Types.INTEGER;
}
}
catch (Exception ex) {
}
try {
if ((byte[]) x != null) {
return Types.VARBINARY;
}
}
catch (Exception ex) {
}
Setting InputStreams
As well see with ResultSet later, using InputStreams is the recommended way to work
with long data (blobs). There are two ways to treat InputStreams when using them as
input parameters: Read the entire InputStream when the parameter is set and treat it as a
large data object, or defer the read until the statement is executed and read it in chunks at
a time. The latter approach is the preferred method because the contents of an
145
InputStream may be too large to fit into memory. Heres what the SimpleText driver
does with InputStreams:
public void setBinaryStream(
int parameterIndex,
java.io.InputStream x,
int length)
throws SQLException
{
try {
x.read(b);
}
catch (Exception ex) {
throw new SQLException("Unable to read InputStream: " +
ex.getMessage());
}
146
And heres the findColumn routine:
public int findColumn(
String columnName)
throws SQLException
{
// Make a mapping cache if we don't already have one
if (md == null) {
md = getMetaData();
s2c = new Hashtable();
}
// Look for the mapping in our cache
Integer x = (Integer) s2c.get(columnName);
if (x != null) {
return (x.intValue());
}
String s = null;
if (inMemoryRows != null) {
s = (getColumn(rowNum, columnIndex)).getString();
}
147
else {
CommonValue value = getValue(colNo);
if (value != null) {
s = value.getString();
}
}
if (s == null) {
lastNull = true;
}
return s;
}
The method starts out by verifying that the given column number is valid. If it is not, an
exception is thrown. Some other types of initialization are also performed. Remember
that all ResultSet objects are provided with a Hashtable of SimpleTextColumn objects
describing each column:
protected int verify(
int column)
throws SQLException
{
clearWarnings();
lastNull = false;
if (col == null) {
throw new SQLException("Invalid column number: " + column);
}
return col.colNo;
}
Next, if the row data is stored in an in-memory Hashtable (as with the
DatabaseMetaData catalog methods), the data is retrieved from the Hashtable.
Otherwise, the driver gets the data from the data file. In both instances, the data is
retrieved as a CommonValue object, and the getString method is used to format the data
into the requested data type. Null values are handled specially; the JDBC API has a
wasNull method that will return true if the last column that was retrieved was null:
public boolean wasNull()
throws SQLException
{
return lastNull;
}
The SimpleText driver also supports InputStreams. In our case, the
SimpleTextInputStream class is just a simple wrapper around a CommonValue object.
Thus, if an application requests the data for a column as an InputStream, the SimpleText
driver will get the data as a CommonValue object (as it always does) and create an
InputStream that fetches the data from the CommonValue.
148
The getMetaData method returns a ResultSetMetaData object, which is our last class to
cover.
ResultSetMetaData
The ResultSetMetaData class provides methods that describe each one of the columns in
a result set. This includes the column count, column attributes, and the column name.
ResultSetMetaData will typically be the smallest class in a JDBC driver, and is usually
very straightforward to implement. For the SimpleText driver, all of the necessary
information is retrieved from the Hashtable of column information that is required for all
result sets. Thus, to retrieve the column name:
public String getColumnLabel(
int column)
throws SQLException
{
// Use the column name
return getColumnName(column);
}
if (column == null) {
throw new SQLException("Invalid column number: " + col);
}
return column;
}
Summary
We have covered a lot of material in this chapter, including the JDBC DriverManager
and the services that it provides, implementing Java interfaces, creating native JDBC
drivers, tracing, data coercion, escape sequence processing, and each one of the major
JDBC interfaces. This information, in conjunction with the SimpleText driver, should
help you to create your own JDBC driver without too much difficulty.
Chapter 11
Internet Database Issues: Middleware
The JDBC specification says that the JDBC API should serve as a platform for building
so-called three-tier client/server systems, often called middleware. As you might
imagine, these systems have three basic components: the client, the server, and the
application server. Figure 11.1 shows the basic structure of a three-tier system.
149
Figure 11.1 Three-tier system structure.
In this chapter, Ill provide you with the code necessary to implement a simple
application server of your own. Well also take a look at building a client for our home-
grown application server. But before we get to the coding, we first need to discuss why
we would want to go to such lengths to build a three-tier system instead of allowing
direct database access.
Several middleware solutions based on the JDBC are already available, and although you
may ultimately decide to buy one from a vendor instead of coding one yourself, I feel that
its important to learn the issues involved with middleware. Knowing the advantages and
disadvantages that go along with inserting a middle tier to a system can help you decide if
you need one.
150
Lets now have a look at how a middle tier can address the issues presented in the
previous section, while adding extra capability to a client/server system:
ConcurrencyYou can program the application
server to handle concurrency issues, off-loading the
task from the database server. Of course, you would
also need to program the clients to respond to update
broadcasts. You can implement concurrency checking
entirely on the application server, if necessary. This
process involves checking to see if a specific data
object requested by a client has changed since the
current request, asking the client to update the
previously retrieved data, and alerting the user.
Legacy DatabasesDatabases that operate on
older network protocols can be piped through an
application server running on a machine that can
communicate with the database server, as well as with
remote Internet clients. A JDBC driver that can speak
to a non-networked legacy database can be used to
provide Internet access to its data, even using an ODBC
driver, courtesy of the JDBC-ODBC Bridge. The
application server can reside on the same machine as
the non-networked database, and provide network
access using a client that communicates to the
application server.
SecurityYou can program/obtain an application
server that supports a secure connection to the remote
clients. If you keep the local connection between the
database server and the application server restricted to
each other, you can create a fairly secure system. In
this type of setup, your database server can only talk
to the application server, so the threat of someone
connecting directly to the database server and causing
damage is greatly limited. However, you must be sure
that there are no loopholes in your application server.
Simultaneous ConnectionsThe application server,
in theory, can maintain only one active connection to
the database server. On the other side, it can allow as
many connections to itself from clients as it wants. In
practice, however, significant speed problems will arise
as more users attempt to use one connection. Managing
a number of fixed connections to the database server is
possible, though, so this speed degradation is not
noticeable.
151
Disadvantages Of Middleware
Of course, middleware is not without its own pitfalls. Lets take a brief look at some
disadvantages you may encounter if you choose to implement an application server:
SpeedAs Ive hinted, speed is the main drawback
to running an application server, especially if the
application server is running on a slow machine. If the
application server does not run on the same machine as
the database server, there may be additional speed loss
as the two communicate with each other.
SecurityIf your application server is not properly
secured, additional security holes could easily crop up.
For example, a rogue user could break into the
application server, then break into the database server
using the application servers functions. Again, you
must take great care to make sure that unauthorized
access to the database server via the application server
is not possible.
ReliabilityAdding an application server to the
system introduces potential problems that may not be
present in a two-tier system, where the clients are
communicating directly with the database server.
The Application Server: A Complete Example With Code
Ive shown you the advantages and disadvantages of implementing an application server;
its up to you to weigh these points and other relating factors when it comes time to make
a decision on your own system. Lets look at a fully functional application server. The
application server shown in Listing 11.1 uses JDBC to interact with data sources, so any
JDBC driver could be used. I used the mSQL driver in this example, but you can easily
modify the code to use the JDBC-ODBC Bridge, and then use the ODBC drivers for
Access 95 to allow applets to query an Access 95 database. (This is an interesting
scenario, because Access does not provide direct network connectivity in the form of a
true database server.) This application server is truly multithreadedit spawns each
client connection into its own thread. Each client connection also make a new instance of
the JDBC driver, so each client has its own virtual connection to the data source via the
application server.
The application server only allows two real functions:
Connect to a predefined data source
Make Select queries against the data source
The query is processed against the data source, and the result is piped directly back to the
client in pre-formatted text. You can easily extend this approach so that a ResultSet can
be encapsulated and sent unprocessed to the client by using the upcoming remote objects
specification from JavaSoft. For the purposes of this example, I wont make it too
elaborate and instead just send over the results in a delimited String format. The client is
152
not a true JDBC client in that it does not implement a JDBC driver; it uses the two
functions defined earlier to make queries. The results can be parsed by the applet calling
the client, but for the purpose of this simple example, well just show them to the user
(youll see this when we show the code for the client).
You can find the source file for Listing 11.1 on the CD-ROM or on The Coriolis Groups
Web site at http://www.coriolis.com/jdbc-book. Figure 11.2 shows the application
servers window.
153
// Create a window to display our connections in
f = new Frame("Server Status");
connection_list = new List();
f.add("Center", connection_list);
f.resize(400, 200);
f.show();
// This class is the thread that handles all communication with a client.
// It also notifies the ConnectionWatcher when the connection is dropped.
class ServerConnection extends Thread {
static int numberOfConnections = 0;
protected Socket client;
protected ConnectionWatcher watcher;
protected DataInputStream in;
protected PrintStream out;
Connection con;
154
// Initialize the streams and start the thread
public ServerConnection(Socket client_socket, ThreadGroup
CurrentConnections,
int priority, ConnectionWatcher watcher) {
// Give the thread a group, a name, and a priority
super(CurrentConnections, "Connection number" +
numberOfConnections++);
this.setPriority(priority);
inline=inline.trim();
// Get rid of leading and trailing whitespace
155
break;
case `S': out.println("Run query: send SQL Query");
out.println("DONE");
inline = in.readLine();
inline=inline.trim();
// This line gets the query sent here, runs its against
// the connected data source, and returns the results in
// formatted text
out.print(RunQuery(inline));
// RunQuery is the method that runs the passed in
// query using the initialized driver and connection.
out.println("DONE");
break;
default: out.println("ERROR - Invalid Request");
out.println("DONE");
}
out.flush();
}
}
catch (IOException e) {}
156
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(QueryLine);
columns=(rs.getMetaData()).getColumnCount();
while(rs.next()) {
Output+=rs.getObject(pos)+" ";
}
Output+="\n";
}
stmt.close();
// con.close();
}
catch( Exception e ) {
e.printStackTrace();
Output=e.getMessage();
}
return Output;
}
// End DB specific stuff
157
}
}
}
out.flush();
// tell the reader we've sent some data/command
synchronized(reader){reader.notify();reader.notifyOn=false;}
while(true) {
158
// We have to wait until the Reader has finished reading, so we
set
// this notifyOn flag in the reader when it has finished reading.
if (reader.notifyOn) {break;}
}
public Reader(DBClient c) {
super("DBclient Reader");
this.client = c;
this.start();
}
DataInputStream in=null;
try {
in = new DataInputStream(client.socket.getInputStream());
while(true) {
// We start reading when we are notified from the main thread
// and we stop when we have finished reading the stream for
// this command/query.
try {if (notifyOn) {this.wait(); notifyOn=false; Result="";}}
catch (InterruptedException e){
System.out.println("Caught an Interrupted Exception");
}
// Prevent simultaneous access
line = in.readLine();
if (line.equalsIgnoreCase("DONE")) {
notifyOn=true;
} else
{
if (line == null) {
System.out.println("Server closed connection.");
break;
} // if NOT null
else {Result+=line+"\n";}
System.out.println("Read from server: "+Result);
} // if NOT done..
} //while loop
}
catch (IOException e) {System.out.println("Reader: " + e);}
finally {
try {if (in != null) in.close();}
catch (IOException e) {
System.exit(0);
159
}
}
}
public String getResult() {
return (Result);
}
}
The client class needs to be instantiated in a Java program, and the connection needs to
be started before any queries can be made. If you remember our Interactive Query Applet
from Chapter 4, this sample applet will certainly look familiar to you.
Listing 11.3 Applet to call our client class.
import java.net.URL;
import java.awt.*;
import java.applet.Applet;
import DBClient;
gridbag.setConstraints(OutputField, Con);
OutputField.setForeground(Color.white);
160
OutputField.setBackground(Color.black);
add(OutputField);
show();
} //init
OutputField.setText(DataConnection.ProcessCommand(QueryField.getText()))
;
return true;
}
}
Summary
In this chapter, we took a brief look at middleware. You saw the advantages and
disadvantages of implementing a three-tier system, and we created a simple application
server and a client server which you can easily extend to fit your needs.
161
Were almost at the end of this journey through the JDBC. The next chapter is a reference
chapter of the JDBC API. It contains documentation on the JDBC methods used in the
writing of this book, as well as methods that we didnt explicitly cover. You may want to
browse through the package tree to get an idea of how the various classes and methods fit
together, as well as their relation to one another.
Chapter 12
The JDBC API
This chapter ends our journey through the JDBC. Ive provided a summary of the class
interfaces and exceptions that are available in the JDBC API version 1.01, which was the
most current version at the time of this writing. Although this chapters primary purpose
is to serve as a reference, you should still read through the sections completely so that
you are aware of all the constructors, variables, and methods available.
Classes
Well begin with the class listings. Each class listing includes a description and the class
constructors, methods, and variables.
public class Date
This class extends the java.util.Date object. But unlike the java util.Date, which stores
time, this class stores the day, year, and month. This is for strict matching with the SQL
date type.
Constructors
Constructor Additional Description
Date(int Year, int Month, int Construct a java.sql.Date
day) object with the appropriate
parameters
Methods
Method Name Additional Description
Formats a Date object as
public String toString()
YYYY-MM-DD
public static Date valueOf Converts a String str to an
(String str) sql.Date object
public class DriverManager
This class is used to load a JDBC driver and establish it as an available driver. It is
usually not instantiated, but is called by the JDBC driver.
162
Constructors
DriverManager()
Methods
Method Name Additional Description
public static void Drops a driver from the
deregisterDriver(Driver- available drivers list
JDBCdriver) throws
SQLException
public static synchronized
Connection
getConnection(String URL)
throws SQLException
public static synchronized
Connection
getConnection(String URL,
String LoginName, String
LoginPassword) throws
SQLException
public static synchronized Establishes a connection to
Connection the given database URL, with
getConnection(String URL, the given parameters
Properties LoginInfo) throws
SQLException
public static Driver Finds a driver that
getDriver(String URL) throws understands the JDBC URL
SQLException from the registered driver list
public static Enumeration Gets an Enumeration of the
getDrivers() available JDBC drivers
public static int Indicates the maximum time
getLoginTimeout() (seconds) that a driver will
wait when logging into a
database
public static PrintStream Gets the logging PrintStream
getLogStream() used by the DriverManager
and JDBC drivers
public static void Sends msg to the current
println(String msg) JDBC logging stream (fetched
from above method)
public static synchronized Specifies that a new driver
163
void register Driver(Driver class should call
JDBCdriver) throws registerDriver when loading
SQLException to register with the
DriverManager
public static void Indicates the time (in
setLoginTimeout(int sec) seconds) that all drivers will
wait when logging into a
database
public static void Define the PrintStream that
setLogStream (PrintStream logging messages are sent to
log) via the println method above
public class DriverPropertyInfo
This class is for developers who want to obtain and set properties for a loaded JDBC
driver. Its not necessary to use this class, but it is useful for debugging JDBC drivers and
advanced development.
Constructors
Constructor Additional Description
public DriverPropertyInfo The propName is the name of
(String propName, String the property, and propValue
propValue) is the current value; if its not
been set, it may be null
Variables
Variable Name Additional Description
choices If the property value is part
of a set of values, then
choices is an array of the
possible values
description The propertys description
name The propertys name
required This is true if this property is
required to be set during
Driver.connect
The current value of the
value
property
public final class Numeric
164
This special fixed-point, high precision number class is used to store the SQL data types
NUMERIC and DECIMAL.
Constructors
Constructor Additional Description
public Numeric(String Produces a Numeric object
strNum) from a string; strNum can be
in one of two formats:
1234.32 or 3.1E8
public Numeric(String strNum, Produces a Numeric, and
int scale) scale is the number of digits
right of the decimal
public Numeric(int intNum) Produces a Numeric object
from an int Java type
parameter
public Numeric(int intNum, int Produces a Numeric object
scale) from an int, and scale gives
the desired number of places
right of the decimal
public Numeric(long x) Produces a Numeric object
from a long Java type
parameter
public Numeric(long x, int Produces a Numeric object
scale) from a long parameter, and
scale gives the desired
number of places right of the
decimal
public Numeric(double x, int Produces a Numeric object
scale) from a double Java type
parameter, and scale gives
the desired number of places
right of the decimal
public Numeric(Numeric num) Produces a Numeric object
from a Numeric
public Numeric(Numeric num, Produces a Numeric object
int scale) from a Numeric, and scale
gives the desired number of
places right of the decimal
Methods
165
Method Name Additional Description
public Numeric add(Numeric Performs arithmetic addition
n) on the reference Numeric
object and the Numeric
argument
public static Numeric Produces a Numeric object
createFromByteArray(byte from the byte array
byteArray[]) parameter
public static Numeric
Produces a Numeric object
createFromIntegerArray(int
from the int array parameter
intArray[])
public static Numeric Produces a Numeric object
createFromRadixString(String from the String and int radix
str, int radix) parameters
public static Numeric Produces a Numeric object by
createFromScaled(long taking the longNum to the
longNum, int power) 10^power
public Numeric Divides the Numeric by the
divide(Numeric q) Numeric parameter q and
returns the result
public double doubleValue() Returns the Numeric as a
Java type double
public boolean equals(Object Returns true if the Numeric
objct) object equals the objct
parameter
Returns the Numeric as a
public float floatValue()
Java type float
public static int Returns the roundingValue
getRoundingValue() used in rounding operations
in the Numeric object
public int getScale() Returns the number of places
to the right of the decimal
public long getScaled() Returns the Numeric object as
a long, but removes the
decimal (1234.567 ->
1234567); precision may be
lost
public boolean Returns true if the Numeric
greaterThan(Numeric num) object is greater than the
166
Numeric num argument
public boolean Returns true if the Numeric
greaterThanOrEquals(Numeric object is greater than or
num) equal to the Numeric num
argument
public int hashCode() Returns an integer hashcode
for the Numeric object
public Numeric[] Returns an array with two
integerDivide(Numeric x) Numeric objects: the first one
is the quotient, the second is
the remainder
public int intValue() Returns the Numeric as a
Java type int, digits after the
decimal are dropped
public boolean Returns true if the number is
isProbablePrime() prime; it divides the Numeric
object by several small
primes, and then uses the
Rabin probabilistic primality
test to test if the number is
primethe failure rate is less
than (1/(4^N))
public boolean Returns true if the Numeric
lessThan(Numeric num) object is less than the
Numeric num argument
public boolean Returns true if the Numeric
lessThanOrEquals(Numeric object is less than or equal to
num) the Numeric num argument
Returns the Numeric as a
public long longValue()
Java type long
public Numeric modExp The two parameters are used
(Numeric numExp, Numeric to do a numMod modulus to
numMod) the numExp exponent
calculation; returns the result
as a Numeric
public Numeric The modular multiplicative
modInverse(Numeric inverse is returned using
numMod) numMod as the modulus
public Numeric Returns the product of the
multiply(Numeric num) Numeric object and the
167
Numeric num parameter
public static Numeric pi(int Returns pi to the number of
places) decimal places
public Numeric pow(int exp) Returns a Numeric object
using the current Numeric
object taken to the power of
the given exponent exp
public static Numeric Returns a Numeric object that
random(int bits, Random is a random number using
randSeed) randSeed as a seed, having
size in bits equal to the bits
parameter
public Numeric Returns the remainder
remainder(Numeric num) resulting from dividing this
Numeric object by the
Numeric num parameter
public static void Sets the rounding value used
setRoundingValue(int val) in rounding operations for the
Numeric object
public Numeric setScale(int Returns a Numeric object
scale) from the current object with
the specified scale parameter
public Numeric shiftLeft(int Returns the Numeric object
numberOfBits) with the specified
numberOfBits shifted left
public Numeric shiftRight(int Returns the Numeric object
numberOfBits) with the specified
numberOfBits shifted right
public int significantBits() Returns the number of
significant bits in the Numeric
object
public Numeric sqrt() Returns the square root of
this Numeric object
public Numeric Returns the difference
subtract(Numeric num) between the Numeric object
and the Numeric num
parameter
public String toString() Returns a String type that is
the String representation of
the Numeric object
168
public String toString(int Returns a String type that is
radix) the String representation of
the Numeric object, in the
specified radix
Variables
Variable Name Additional Description
public final static Numeric A Numeric equivalent to the
ZERO value of 0
public final static Numeric A Numeric equivalent to the
ONE value of 1
public class Time
The public class Time is another SQL-JDBC data coversion class. This class extends
java.util.Date, and basically implements the time-storing functions that are not present in
the java.sql.Date class shown earlier.
Constructors
Constructor Additional Description
public Time(int hour, int Makes a Time object with the
minute, specified hour, minute, and
int second) second
Methods
Method Name Additional Description
public String toString() Returns a String with the
Time formatted this way:
HH:MM:SS
public static Time Returns a Numeric object
valueOf(String numStr) from the String numStr
parameter that is in the
format: HH:MM:SS
public class TimeStamp
This class is used to map the SQL data type TIMESTAMP. It extends java.util.Date, and
has nanosecond precision for time-stamping purposes.
Constructors
Constructor Additional Description
public Timestamp(int year, int Builds a Timestamp object
169
month, int date, int hour, int using the int parameters:
minute, int second, int nano) year, month, date, hour,
minute, second, and nano
Methods
Method Name Additional Description
public boolean Compares the Timestamp
equals(Timestamp tstamp) object with the Timestamp
parameter tstamp; returns
true if they match
Returns the Timestamp
public int getNanos()
objects nanoseconds
Sets the Timestamp objects
public void setNanos(int n)
nanosecond value
public String toString() Returns a formatted String
object with the value of the
Timestamp object in the
format: YYYY-MM-DD
HH:MM:SS.F
public static Timestamp Returns a Timestamp object
valueOf(String strts) converted from the strts
parameter that is in the
previous format
public class Types
This class contains the SQL data types as constants. It is used by other classes as the
standard constant for the data types.
Constructors
Constructor Additional Description
public Types() Builds a Types object; not
usually necessary as they can
be accessed as so:
Types.BIGINT
Variables
BIGINT
BINARY
BIT
CHAR
DATE
170
DECIMAL
DOUBLE
FLOAT
INTEGER
LONGVARBINARY
LONGVARCHAR
NULL
NUMERIC
OTHER (for a database specific data type, not a
standard SQL-92 data type)
REAL
SMALLINT
TIME
TIMESTAMP
TINYINT
VARBINARY
VARCHAR
Interfaces
Next are the interface listings. As with the class listings, each interface listing includes a
description and the interfaces methods and variables.
public interface CallableStatement
This is the primary interface to access stored procedures on a database. If OUT
parameters are specified and a query is executed via this class, its results are fetched from
this class and not the ResultSet class. This class extends the PreparedStatement class,
thus inheriting many of its methods.
The first 15 methods (the get methods) are identical in functionality to those in the
ResultSet class, but they are necessary if OUT parameters are used. See the ResultSet
class for a description of the methods.
Methods
Method Name Additional Description
public abstract boolean
getBoolean(int
parameterIndex) throws
SQLException
public abstract byte
getByte(int parameterIndex)
throws SQLException
public abstract byte[]
getBytes(int parameterIndex)
171
throws SQLException
public abstract Date
getDate(int parameterIndex)
throws SQLException
public abstract double
getDouble(int
parameterIndex) throws
SQLException
public abstract float
getFloat(int parameterIndex)
throws SQLException
public abstract int getInt(int
parameterIndex) throws
SQLException
public abstract long
getLong(int parameterIndex)
throws SQLException
public abstract Numeric
getNumeric(int
parameterIndex, int scale)
throws SQLException
public abstract Object
getObject(int
parameterIndex) throws
SQLException
public abstract short
getShort(int parameterIndex)
throws SQLException
public abstract String
getString(int parameterIndex)
throws SQLException
public abstract Time
getTime(int parameterIndex)
throws SQLException
public abstract Timestamp
getTimestamp(int
parameterIndex) throws
SQLException
public abstract void Each parameter of the stored
registerOutParameter(int procedure must be registered
172
paramIndex, int sqlDataType) before the query is run;
throws SQLException paramIndex is the stored
procs parameter location in
the output sequence, and
sqlDataType is the data type
of the parameter at the
specified location
(sqlDataType should be set
from the Type class using one
of its variables, for example,
Types.BIGINT)
public abstract void Specifies the number of
registerOutParameter(int places to the right of the
parameterIndex, int decimal desired when getting
sqlDataType, int scale) throws Numeric data objects
SQLException
public abstract boolean Returns true if the stored
wasNull() throws proc parameter was value
SQLException NULL
public interface Connection
This is the high-level class used to interact with a database. The object is established from
the DriverManager.getConnection method, which returns this object (Connection).
This class obtains information about the specific database connection via the instantiated
JDBC driver, and its primary use is to perform queries via the createStatement,
prepareCall, and prepareStatement methods, which return Statement, PreparedCall,
and PreparedStatement objects, respectively.
Methods
Method Name Additional Description
public abstract void Clears the warnings for the
clearWarnings() throws connection
SQLException
public abstract void close() Closes the connection to the
throws SQLException database
public abstract void commit() Functions as the JDBC
throws SQLException equivalent of the standard
database commit command; it
applies all commands and
changes made since the last
173
commit or rollback, including
releasing database locks;
results from queries are
closed when commit is
invoked
public abstract Statement Returns a Statement object,
createStatement() throws which can then be used to
SQLException perform actual queries
public abstract boolean Returns true if automatic
getAutoClose() throws closing of the connection is
SQLException enabled; automatic closing
results in the closing of the
connection when commit or
rollback is performed
public abstract boolean Returns true if automatic
getAutoCommit() throws committing of the connection
SQLException is on; automatic commit is on
by default and means that the
connection is committed on
individual transactions; the
actual commit occurs when
the last row of a result set is
fetched, or when the
ResultSet is closed
public abstract String Returns the current catalog
getCatalog() throws name for the connection
SQLException
public abstract Returns a DatabaseMetaData
DatabaseMetaData object for the current
getMetaData() throws connection
SQLException
public abstract int Returns the transaction
getTransactionIsolation() isolation mode of the
throws SQLException connection
public abstract SQLWarning Returns the SQLWarning
getWarnings() throws object with the warnings for
SQLException the connection
public abstract boolean Returns true if the connection
isClosed() throws has been closed
SQLException
public abstract boolean Returns true if the connection
174
isReadOnly() throws is a read only connection
SQLException
public abstract String Returns the native SQL that
nativeSQL(String throws the JDBC driver sqlQuery)
SQLException would send to the database
for the specified sqlQuery
parameter
public abstract Returns a CallableStatement
CallableStatement object used to perform stored
prepareCall(String sqlQuery) procedures; note that the SQL
throws SQLException query must be passed in as
the sqlQuery parameter here
public abstract Returns a PreparedStatement
PreparedStatement object used to perform the
prepareStatement(String specified sqlQuery; this query
sqlQuery) throws can be executed repeatedly if
SQLException desired by using the
PreparedStatement.execute
method
public abstract void rollback() Drops changes made since the
throws SQLException last commit or rollback, and
closes respective results;
database locks are also
released
public abstract void Sets the connection to auto
setAutoClose (boolean throws close mode if the auto) auto
SQLException parameter is true
public abstract void throws Sets the connection to auto
SQLException commit mode if
setAutoCommit(boolean auto)
the auto parameter is true
public abstract void The catalog may be changed
setCatalog (String catalog) by specifying the catalog
throws SQLException
public abstract void Sets the connection to read
setReadOnly(boolean only mode
readOnly) throws
SQLException
public abstract void Sets translation isolation to
setTransactionIsolation(int the specified level
level) throws SQLException
175
Variables
The following constants are used in the setTransactionIsolation method as the level
parameter:
TRANSACTION_NONE
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE
public interface DatabaseMetaData
This class contains useful information about the open connection to the database. The
Connection.getMetaData method returns a Database-MetaData object that is specific
to the opened connection.
Methods
Method Name Additional Description
public abstract boolean Returns true if all the
allProceduresAreCallable() throwsk procedures available to
SQLException the user are callable
public abstract boolean Returns true if all of the
allTablesAreSelectable() throws tables are accessible to
SQLException the user on the open
connection
public abstract boolean Returns true if data
dataDefinitionCausesTransactionCommit() defintion causes the
throws SQLException transaction to commit
public abstract boolean Returns true if data
dataDefinitionIgnoredInTransactions() defintion is ignored in
throws SQLException the transaction
public abstract boolean Returns true if the
doesMaxRowSizeIncludeBlobs() throws getMaxSize method does
SQLException not account for the size
of LONGVARCHAR and
LONGVARBINARY SQL
data types
public abstract ResultSet Returns a ResultSet
getBestRowIdentifier(String catalog, object for the specified
String parameters that gets the
schema, String table, int scope, boolean specified tables key or
176
nullok) throws SQLException the attributes that can
be used to uniquely
identify a row, which
may be composite; the
scope parameter is one
of the constants:
bestRowTemporary,
bestRowTransaction, or
betRowSession; the
nullok parameter allows
columns that may be
null; the ResultSet is
composed of the
following columns: scope
(of the same types as
above scope parameter),
column name, SQL data
type, name of the data
type dependent on the
database, precision,
buffer length, significant
places if a Numeric type,
and pseudo column (one
of the constants
bestRowUnknown,
bestRowNotPseudo, or
bestRowPseudo)
public abstract ResultSet getCatalogs() Returns a ResultSet
throws SQLException object that contains a
column for the catalog
names that are in the
database
public abstract Returns the separator
String getCatalogSeparator() throws between the catalog
SQLException String and the table
name
public abstract String getCatalogTerm() Returns the database-
throws SQLException specific term for
catalog
public abstract ResultSet Returns a ResultSet
getColumnPrivileges(String catalog, object that contains
String schemaString table, String information about the
177
columnNamePattern) throws specified tables
SQLException matching
columnNamePattern; the
returned ResultSet object
contains the following
columns: the catalog
name that the table is in,
the schema the table is
in, the table name, the
column name, owner of
the table, grantee, type
of access (SELECT,
UPDATE, etc.), and if the
grantee can grant access
to others, YES, NO,
or null (if unknown)
public abstract ResultSet Returns a ResultSet
getColumns(String catalog, object that contains
String schemaPattern, String information about the
tableNamePattern, matching columns for the
String columnNamePattern) throws matching tables and
SQLException schemas; the ResultSet
contains the following
columns: catalog name,
schema name, table
name, column name, SQL
data type, name of the
type specific to the
database, the maximum
number of characters or
precision depending on
the data type, buffer
length (not used), the
number of digits (if
applicable), radix (if
applicable), null-ability
(one of the constants
columnNoNulls,
columnNullable,
columnNullableUnknown),
comments for the
column, default value (if
it exists, else null),
178
empty column, empty
column, maximum
number of bytes in the
column of type CHAR (if
applicable), index
number of column; the
last column is set to
YES if it can contain
NULLS if not NO else
its empty if the status is
unknown
public abstract ResultSet get Returns a ResultSet
CrossReference(String primaryCatalog, object that describes the
String primarySchema, way a table imports
String primaryTable, String foreign keys; the
foreignCatalog, ResultSet object returned
String foreignSchema, String by this method contains
foreignTable) these columns: primary
throws SQLException keys table catalog,
primary keys table
schema, primary keys
table, primary keys
column name, foreign
keys table catalog,
foreign keys table
schema, foreign keys
table, foreign keys
column name, sequence
number within foreign
key, action to foreign key
when primary key is
updated (one of the
constants
importedKeyCascade,
importedKeyRestrict,
importedKeySetNull),
action to foreign key
when primary key is
deleted (one of the
constants
importedKeyCascade,
importedKeyRestrict,
importedKeySetNull),
179
foreign key identifier,
and primary key
indentifier
public abstract String Returns the database
getDatabaseProductName() throws product name
SQLException
public abstract String Returns the database
getDatabaseProductVersion() throws product number
SQLException
public abstract int Returns the default
getDefaultTransactionIsolation() throws transaction isolation
SQLException level as defined by the
applicable constants in
the Connection class
public abstract int Gets the drivers major
getDriverMajorVersion() version
public abstract int Gets the drivers minor
getDriverMinorVersion() version
public abstract String getDriverName() Returns the name of the
throws SQLException JDBC driver
public abstract String getDriverVersion() Returns the version of
throws SQLException the JDBC driver
public abstract ResultSet Returns a ResultSet
getExportedKeys(String catalog, String object that describes the
schema, String table) throws foreign key attributes
SQLException that reference the
specified tables primary
key; the ResultSet object
returns the following
columns: primary keys
table catalog, primary
keys table schema,
primary keys table,
primary keys column
name, foreign keys table
catalog, foreign keys
table schema, foreign
keys table, foreign keys
column name, sequence
number within foreign
key, action to foreign key
180
when primary key is
updated (one of the
constants
importedKeyCascade,
importedKeyRestrict,
importedKeySetNull),
action to foreign key
when primary key is
deleted (one of the
constants
importedKeyCascade,
importedKeyRestrict,
importedKeySetNull),
foreign key identifier,
and primary key
indentifier
public abstract String Returns characters that
getExtraNameCharacters() throws can be used in unquoted
SQLException identifier names besides
the standard A through
Z, 0 through 9, and _
public abstract String Returns the String used
getIdentifierQuoteString() throws to quote SQL identifiers
SQLException
public abstract ResultSet Returns a ResultSet
getImportedKeys(String String schema, object that describes the
String table) throws SQLException primary key attributes
that are referenced by
the specified tables
foreign key attributes;
the ResultSet object
contains the following
columns: primary keys
table catalog, primary
keys table schema,
primary keys table,
primary keys column
name, foreign keys table
catalog, foreign keys
table schema, foreign
keys table, foreign keys
column name, sequence
number within foreign
181
key, action to foreign key
when primary key is
updated (one of the
constants
importedKeyCascade,
importedKeyRestrict,
importedKeySetNull),
action to foreign key
when primary key is
deleted (one of the
constants
importedKeyCascade,
importedKeyRestrict,
importedKeySetNull),
foreign key identifier,
and primary key
indentifier
public abstract ResultSet Returns a ResultSet
getIndexInfo(String catalog, String object that describes the
schema, String table, boolean unique, specified tables indices
boolean approximate) throws and statistics; the
SQLException ResultSet object contains
the following columns:
catalog name, schema
name, table name,
false boolean (if
tableIndexStatic is the
type), index catalog (or
null if type is
tableIndexStatic), index
type, sequence number,
column name, column
sort sequence, number of
unique values in the
table or number of rows
(if tableIndexStatic),
number of pages used for
the index (or the number
of pages used for the
table if
tableIndexStatic), and
filter condition (if it
exists)
182
public abstract int Returns the number of
getMaxBinaryLiteralLength() throws hex characters allowed in
SQLException an inline binary literal
public abstract int The maximum length for
getMaxCatalogNameLength() throws a catalog name
SQLException
public abstract int Returns the maximum
getMaxCharLiteralLength() throws length for a character
SQLException literal
public abstract int Indicates the maximum
getMaxColumnNameLength() throws length for a column name
SQLException
public abstract int Indicates the maximum
getMaxColumnsInGroupBy() throws number of columns in a
SQLException GROUP BY clause
public abstract int Indicates the maximum
getMaxColumnsInIndex() throws number of columns in an
SQLException index
public abstract int Indicates the maximum
getMaxColumnsInOrderBy() throws number of columns
SQLException allowed in a ORDER BY
clause
public abstract int Indicates the maximum
getMaxColumnsInSelect() throws number of columns in a
SQLException SELECT statement
public abstract int Indicates the maximum
getMaxColumnsInTable() throws number of columns
SQLException allowed in a table
public abstract int getMaxConnections() Indicates the maximum
throws SQLException number of simultaneous
connections allowed to
the database
public abstract int Returns the maximum
getMaxCursorNameLength() throws allowed length of a
SQLException cursor name
public abstract int Returns the maximum
getMaxIndexLength() throws length of an index in
SQLException bytes
public abstract int Returns the maximum
getMaxProcedureNameLength() throws allowed length of a
183
SQLException procedure name
public abstract int getMaxRowSize() Indicates the maximum
throws SQLException row size
public abstract int Returns the maximum
getMaxSchemaNameLength() throws allowed length of a
SQLException schema name
public abstract int Returns the maximum
getMaxStatementLength() throws allowed length of a SQL
SQLException statement
Returns the maximum
public abstract int getMaxStatements()
number of statements
throws SQLException
allowed at one time
public abstract int Returns the maximum
getMaxTableNameLength() throws allowed length of a table
SQLException name
public abstract int Indicates the maximum
getMaxTablesInSelect() number of tables allowed
throws SQLException in a SELECT statement
public abstract int Returns the maximum
getMaxUserNameLength() throws allowed length of a user
SQLException name
public abstract String Returns a comma-
getNumericFunctions() throws separated list of the
SQLException math functions available
public abstract Returns a ResultSet
ResultSet getPrimaryKeys(String catalog, object that contains the
String schema, String table) throws primary keys description
SQLException for the specified table;
the ResultSet object
contains the following
columns: catalog name,
schema name, table
name, column name,
sequence number,
primary key name, and,
possibly, NULL
public abstract ResultSet Returns a ResultSet
getProcedureColumns(String catalog, object that describes the
String schemaPattern, String catalogs stored
procedureNamePattern, String procedures and result
184
columnNamePattern) throws columns matching the
SQLException specified
procedureNamePatten
and columnNamePattern;
the ResultSet object
contains the following
columns: catalog name,
schema name, procedure
name, column or
parameter name, column
type, data type, data
name, precision, length
in bytes, scale, radix,
nullability, and
comments
public abstract ResultSet Returns a ResultSet
getProcedures(String catalogString String object that describes the
procedureNamePattern) throws catalogs procedures; the
SQLException ResultSet object contains
the following columns:
catalog name, schema
name, procedure name,
empty column, empty
column, empty column,
comments about the
procedure, and kind of
procedure
public abstract String Return the database-
getProcedureTerm() throws SQLException specific term for
procedure
public abstract ResultSet getSchemas() Returns a ResultSet
throws SQLException object that describes the
schemas in a database;
the ResultSet object
contains one column that
contains the schema
names
public abstract String Returns the database-
getSchemaTerm() throws specific term for schema
SQLException
public abstract String Returns the escape
getSearchStringEscape() throws characters for pattern
185
SQLException searching
public abstract String getSQLKeywords() Returns a comma-
throws SQLException separated list of
keywords that the
database recognizes, but
the keywords are not
SQL-92 keywords
public abstract String Returns a comma-
getStringFunctions() separated list of string
throws SQLException functions in the database
public abstract String Returns a comma-
getSystemFunctions() throws separated list of system
SQLException functions in the database
public abstract ResultSet Returns a ResultSet
getTablePrivileges(String catalog, String object that describes the
schemaPattern schemaPattern, String privileges for the
tableNamePattern) matching and
throws SQLException tableNamePattern; the
ResultSet object contains
the following columns:
catalog name, schema
name, table name,
grantor, grantee, type of
access, and YES if a
grantee can grant other
access
public abstract ResultSet Returns a ResultSet
getTables(String object that describes
catalog, String schemaPattern, String tables matching the
tableNamePattern, String types[]) schemaPattern and
throws SQLException tableNamePattern; the
ResultSet object contains
the following columns:
catalog name, schema
name, table name, table
type, and comments
public abstract ResultSet getTableTypes() Returns a ResultSet
throws SQLException object that describes the
table types available in
the database; the
ResultSet object contains
the column that is a list
186
of the table types
public abstract String Returns the date and
getTimeDateFunctions() throws time functions for the
SQLException database
public abstract ResultSet getTypeInfo() Returns a ResultSet
throws SQLException object that describes the
SQL data types
supported by the
database; the ResultSet
object contains the
columns: type name, SQL
data type constants in
the Types class,
maximum precision,
prefix used to quote a
literal, suffix used to
quote a literal,
parameters used to
create the type,
nullability, case
sensitivity, searchability,
signed or unsigned
(boolean), is it a
currency, auto
incrementable or not,
local version of data
type, minimum scale,
maximum scale, empty
column, empty column,
and radix
public abstract String getURL() throws The URL for the database
SQLException
public abstract String getUserName() Returns the user name as
throws SQLException known by the database
public abstract ResultSet Returns a ResultSet
getVersionColumns(String catalog, object that describes the
String String table) throws SQLException specified tables columns
that are updated when
any column is updated in
the table; the ResultSet
object contains the
following columns: empty
187
columns, column name,
SQL datatype, type
name, precision, column
value length in bytes,
scale, and pseudoColumn
or not
public abstract boolean isCatalogAtStart() Returns true if the
throws SQLException catalog name appears at
the start of a qualified
table name
public abstract boolean isReadOnly() Returns true if the
throws SQLException database is in read only
mode
public abstract boolean Returns true if a
nullPlusNonNullIsNull() throws concatenation between a
SQLException NULL and non-NULL is
NULL
public abstract boolean
nullsAreSortedAtEnd()
throws SQLException
public abstract boolean
nullsAreSortedAtStart()
throws SQLException
public abstract boolean
nullsAreSortedHigh()
throws SQLException
public abstract boolean
nullsAreSortedLow()
throws SQLException
public abstract boolean
storesLowerCaseIdentifiers()
throws SQLException
public abstract boolean
storesLowerCaseQuotedIdentifiers()
throws SQLException
public abstract boolean
storesMixedCaseIdentifiers() throws
SQLException
public abstract boolean
storesMixedCaseQuotedIdentifiers()
188
throws SQLException
public abstract boolean
storesUpperCaseIdentifiers()
throws SQLException
public abstract boolean
storesUpperCaseQuotedIdentifiers()
throws SQLException
public abstract boolean
supportsAlterTableWithAddColumn()
throws SQLException
public abstract boolean
supportsAlterTableWithDropColumn()
throws SQLException
public abstract boolean
supportsAlterTableWithDropColumn()
throws SQLException
public abstract boolean
supportsANSI92EntryLevelSQL() throws
SQLException
public abstract boolean
supportsANSI92FullSQL() throws
SQLException
public abstract boolean
supportsANSI92IntermediateSQL() throws
SQLException
public abstract boolean
supportsANSI92FullSQL() throws
SQLException
public abstract boolean
supportsCatalogsInDataManipulation()
throws SQLException
public abstract boolean
supportsCatalogsInIndexDefinitions()
throws SQLException
public abstract boolean
supportsCatalogsInPrivilegeDefinitions()
throws SQLException
public abstract boolean
supportsCatalogsInProcedureCalls()
throws SQLException
189
public abstract boolean
supportsCatalogsInTableDefinitions()
throws SQLException
public abstract boolean
supportsColumnAliasing() throws
SQLException
public abstract boolean
supportsConvert() throws SQLException
public abstract boolean
supportsConvert(int fromType, int
toType) throws SQLException
public abstract boolean
supportsCoreSQLGrammar() throws
SQLException
public abstract boolean
supportsCorrelatedSubqueries() throws
SQLException
public abstract boolean
supportsDataDefinitionAnd
DataManipulationTransactions() throws
SQLException
public abstract boolean
supportsDataManipulation
TransactionsOnly() throws SQLException
public abstract boolean
supportsDifferentTableCorrelationNames()
throws SQLException
public abstract boolean
supportsExpressionsInOrderBy() throws
SQLException
public abstract boolean
supportsExtendedSQLGrammar() throws
SQLException
public abstract boolean
supportsFullOuterJoins() throws
SQLException
public abstract boolean
supportsGroupBy() throws SQLException
public abstract boolean
supportsGroupByBeyondSelect() throws
190
SQLException
public abstract boolean
supportsGroupByUnrelated() throws
SQLException
public abstract boolean
supportsIntegrityEnhancementFacility()
throws SQLException
public abstract boolean
supportsLikeEscapeClause() throws
SQLException
public abstract boolean
supportsLimitedOuterJoins() throws
SQLException
public abstract boolean
supportsMinimumSQLGrammar() throws
SQLException
public abstract boolean
supportsMixedCaseIdentifiers() throws
SQLException
public abstract boolean
supportsMixedCaseQuotedIdentifiers()
throws SQLException
public abstract boolean
supportsMultipleResultSets() throws
SQLException
public abstract boolean
supportsMultipleTransactions() throws
SQLException
public abstract boolean
supportsNonNullableColumns() throws
SQLException
public abstract boolean
supportsOpenCursorsAcrossCommit()
throws SQLException
public abstract boolean
supportsOpenCursorsAcrossRollback()
throws SQLException
public abstract boolean
supportsOpenStatementsAcrossCommit()
throws SQLException
191
public abstract boolean
supportsOpenStatementsAcrossRollback()
throws SQLException
public abstract boolean
supportsOrderByUnrelated()
throws SQLException
public abstract boolean
supportsOuterJoins()
throws SQLException
public abstract boolean
supportsPositionedDelete()
throws SQLException
public abstract boolean
supportsPositionedUpdate()
throws SQLException
public abstract boolean
supportsSchemasInDataManipulation()
throws SQLException
public abstract boolean
supportsSchemasInProcedureCalls()
throws SQLException
public abstract boolean
supportsSchemasInProcedureCalls()
throws SQLException
public abstract boolean
supportsSchemasInTableDefinitions()
throws SQLException
public abstract boolean
supportsSelectForUpdate()
throws SQLException
public abstract boolean
supportsStoredProcedures()
throws SQLException
public abstract boolean
supportsSubqueriesInComparisons()
throws SQLException
public abstract boolean
supportsSubqueriesInExists()
throws SQLException
public abstract boolean
192
supportsSubqueriesInIns()
throws SQLException
public abstract boolean
supportsSubqueriesInQuantifieds()
throws SQLException
public abstract boolean
supportsTableCorrelationNames() throws
SQLException
public abstract boolean
supportsTransactionIsolationLevel(int
level) throws SQLException
public abstract boolean
supportsTransactions() throws
SQLException
public abstract boolean
supportsUnion() throws SQLException
public abstract boolean
supportsUnionAll() throws SQLException
public abstract boolean
usesLocalFilePerTable() throws
SQLException
public abstract boolean
usesLocalFiles() throws SQLException
Variables
public final static int bestRowNotPseudo
public final static int bestRowPseudo
public final static int versionColumnUnknown
public final static int versionColumnNotPseudo
public final static int versionColumnPseudo
public final static int importedKeyCascade
public final static int importedKeyRestrict
public final static int importedKeySetNull
primary key has been updated or deleted
public final static int typeNoNulls
public final static int typeNullable
public final static int typeNullableUnknown
public final static int typePredNone
public final static int typePredChar
public final static int typePredBasic
193
public final static int typeSearchable
public final static short tableIndexStatistic
public final static short tableIndexClustered
public final static short tableIndexHashed
public final static short tableIndexOther
public interface Driver
The JDBC driver implements this interface. The JDBC driver must create an instance of
itself and then register with the DriverManager.
Methods
Method Name Additional Description
public abstract boolean Returns true if the driver can
acceptsURL(String URL) connect to the specified
throws SQLException database in the URL
public abstract Connection Connects to the database
connect(String url, Properties specified in the URL with the
props) throws SQLException specified Properties props
public abstract int Returns the JDBC drivers
getMajorVersion() major version number
public abstract int Returns the JDBC drivers
getMinorVersion() minor version number
public abstract Returns an array of
DriverPropertyInfo[] DriverPropertyInfo that
getPropertyInfo(String URL, contains possible properties
Properties props) throws based on the supplied URL
SQLException and props
public abstract boolean Returns true if the JDBC
jdbcCompliant() driver can pass the JDBC
compliance suite
public interface PreparedStatement
This object extends Statement, and it is used to perform queries that will be repeated.
This class exists primarily to optimize queries that will be executed repeatedly.
Methods
194
public abstract void Resets all of the
clearParameters() throws PreparedStatments query
SQLException parameters
public abstract boolean Runs the prepared query
execute() throws against the database; this
SQLException method is used primarily if
multiple ResultSets are
expected
public abstract ResultSet Executes the prepared query
executeQuery() throws
SQLException
public abstract int Executes the prepared query;
executeUpdate() throws this method is used for
SQLException queries that do not produce a
ResultSet (such as Update);
returns the number or rows
affected or 0 if nothing is
returned by the SQL command
public abstract void
setAsciiStream(int
paramIndex, InputStream
paramType, int length) throws
SQLException
public abstract void
setBinaryStream(int
paramIndex, InputStream
paramType, int length) throws
SQLException
public abstract void
setBoolean(int paramIndex,
boolean paramType) throws
SQLException
public abstract void
setByte(int paramIndex, byte
paramType) throws
SQLException
public abstract void
setBytes(int paramIndex,
byte paramType[]) throws
SQLException
public abstract void
195
setDate(int paramIndex, Date
paramType) throws
SQLException
public abstract void
setDouble(int double
paramType) throws
SQLException
public abstract void
setFloat(int paramIndex, float
paramType) throws
SQLException
public abstract void setInt(int
paramIndex, int paramType)
throws SQLException
public abstract void
setLong(int paramIndex, long
paramType) throws
SQLException
public abstract void
setNull(int paramIndex, int
sqlType) throws SQLException
public abstract void
setNumeric(int paramIndex,
Numeric paramType) throws
SQLException
public abstract void
setObject(int paramIndex,
Object paramType) throws
SQLException
public abstract void
setObject(int paramIndex,
Object paramType, int
targetSqlType) throws
SQLException
public abstract void
setObject(int paramIndex,
Object paramType, int
targetSqlType, int scale)
throws SQLException
public abstract void
196
setShort(int paramIndex,
short paramType) throws
SQLException
public abstract void
setString(int paramIndex,
String paramType) throws
SQLException
public abstract void
setTime(int paramIndex, Time
paramType) throws
SQLException
public abstract void
setTimestamp(int
TimestampparamType) throws
SQLException
public abstract void
setUnicodeStream(int
paramIndexInputStream
paramType, int length) throws
SQLException
public interface ResultSet
The results of a query are stored in this object, which is returned when the respective
query execute method is run for the Statement, PreparedStatement, and
CallableStatement methods. The get methods in this class fetch the result for the
specified column, but the proper data type must be matched for the column. The
getMetaData method in this class can facilitate the process of checking the data type in
each column of the result set.
Methods
Method Name Additional Description
public abstract void Clears the warnings for the
clearWarnings() throws ResultSet
SQLException
public abstract void close() Closes the ResultSet
throws SQLException
public abstract int Gets the column number for
findColumn(String the specified columnName in
columnName) throws the ResultSet
197
SQLException
public abstract Returns a ResultSetMetaData
ResultSetMetaData object that contains
getMetaData() throws information about the querys
SQLException resulting table
Fetches the result from the
public abstract InputStream
current row in the specified
getAsciiStream(int
column (the column number -
columnIndex) throws
columnIndex) in the resulting
SQLException
table
Fetches the result from the
public abstract InputStream
current row in the specified
getAsciiStream(String
column (the column name -
columnName) throws
columnName) in the resulting
SQLException
table
Fetches the result from the
public abstract InputStream
current row in the specified
getBinaryStream(int
column (the column number -
columnIndex) throws
columnIndex) in the resulting
SQLException
table
Fetches the result from the
public abstract InputStream
current row in the specified
getBinaryStream(String
column (the column name -
columnName) throws
columnName) in the resulting
SQLException
table
public abstract boolean Fetches the result from the
getBoolean(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
public abstract boolean Fetches the result from the
getBoolean(String current row in the specified
columnName) throws column (the column name -
SQLException columnName) in the resulting
table
public abstract byte Fetches the result from the
getByte(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
public abstract byte Fetches the result from the
198
getByte(String columnName) current row in the specified
throws SQLException column (the column name -
columnName) in the resulting
table
public abstract byte[] Fetches the result from the
getBytes(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
public abstract byte[] Fetches the result from the
getBytes(String columnName) current row in the specified
throws SQLException column (the column name -
columnName) in the resulting
table
public abstract String
This returns a String with this
getCursorName() throws
ResultSets cursor name
SQLException
public abstract Date Fetches the result from the
getDate(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
public abstract Date Fetches the result from the
getDate(String columnName) current row in the specified
throws SQLException column (the column name -
columnName) in the resulting
table
public abstract double Fetches the result from the
getDouble(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
public abstract double Fetches the result from the
getDouble(String current row in the specified
columnName) throws column (the column name -
SQLException columnName) in the resulting
table
public abstract float Fetches the result from the
getFloat(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
199
table
public abstract float Fetches the result from the
getFloat(String columnName) current row in the specified
throws SQLException column (the column name -
columnName) in the resulting
table
public abstract int getInt(int Fetches the result from the
columnIndex) throws current row in the specified
SQLException column (the column number -
columnIndex) in the resulting
table
public abstract int Fetches the result from the
getInt(String columnName) current row in the specified
throws SQLException column (the column name -
columnName) in the resulting
table
public abstract long Fetches the result from the
getLong(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
public abstract long Fetches the result from the
getLong(String columnName) current row in the specified
throws SQLException column (the column name -
columnName) in the resulting
table
Fetches the result from the
public abstract Numeric
current row in the specified
getNumeric(int columnIndex,
column (the column number -
int scale) throws
columnIndex) in the resulting
SQLException
table
Fetches the result from the
public abstract Numeric
current row in the specified
getNumeric(String
column (the column name -
columnName, int scale)
columnName) in the resulting
throws SQLException
table
public abstract Object Fetches the result from the
getObject(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
200
public abstract Object Fetches the result from the
getObject(String current row in the specified
columnName) throws column (the column name -
SQLException columnName) in the resulting
table
public abstract short Fetches the result from the
getShort(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
public abstract short Fetches the result from the
getShort(String columnName) current row in the specified
throws SQLException column (the column name -
columnName) in the resulting
table
public abstract String Fetches the result from the
getString(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
public abstract String Fetches the result from the
getString(String current row in the specified
columnName) throws column (the column name -
SQLException columnName) in the resulting
table
public abstract Time Fetches the result from the
getTime(int columnIndex) current row in the specified
throws SQLException column (the column number -
columnIndex) in the resulting
table
public abstract Time Fetches the result from the
getTime(String columnName) current row in the specified
throws SQLException column (the column name -
columnName) in the resulting
table
public abstract Timestamp Fetches the result from the
getTimestamp (int current row in the specified
columnIndex) throws column (the column number -
SQLException columnIndex) in the resulting
table
public abstract Timestamp Fetches the result from the
201
getTimestamp(String current row in the specified
columnName) throws column (the column name -
SQLException columnName) in the resulting
table
Fetches the result from the
public abstract InputStream
current row in the specified
getUnicodeStream(int
column (the column number -
columnIndex) throws
columnIndex) in the resulting
SQLException
table
Fetches the result from the
public abstract InputStream
current row in the specified
getUnicodeStream(String
column (the column name -
columnName) throws
columnName) in the resulting
SQLException
table
public abstract SQLWarning Returns the warnings for the
getWarnings() throws ResultSet
SQLException
public abstract boolean next() Retrieves the next row of the
throws SQLException resulting table
public abstract boolean Returns true if the last
wasNull() throws column read by one of the get
SQLException methods was NULL
Methods
Method Name Additional Description
public abstract String
Returns the name of the
getCatalogName(int column)
catalog hit by the query
throws SQLException
public abstract int
Returns the number of
getColumnCount() throws
columns in the resulting table
SQLException
public abstract int Returns the specified
getColumnDisplaySize(int columns maximum size
column) throws SQLException
public abstract String Gets a label, if it exists, for
202
getColumnLabel(int column) the specified column in the
throws SQLException result set
public abstract String Gets a name for the specific
getColumnName(int column) column number in the
throws SQLException resulting table
public abstract int Returns a constant in the
getColumnType(int column) Type class that is the JDBC
throws SQLException type of the specified column
in the result set
public abstract String Gets the name of the type of
getColumnTypeName(int the specified column in the
column) throws SQLException result set
public abstract int Returns the precision of the
getPrecision(int column) data in the specified column,
throws SQLException if applicable
public abstract int Returns the scale of the data
getScale(int column) throws in the specified column, if
SQLException applicable
public abstract String Returns the name of the
getSchemaName(int column) schema that was accessed in
throws SQLException the query to produce the
result set for the specific
column
Returns the name of the table
public abstract String
from which the specified
getTableName(int column)
column in the result set came
throws SQLException
from
public abstract boolean Returns true if the specified
isAutoIncrement (int column) column is automatically
throws SQLException numbered
public abstract boolean Returns true if the specified
isCaseSensitive (int column) columns contents are case
throws SQLException sensitive, if applicable
public abstract boolean Returns true if the content of
isCurrency(int column) throws the specific column in the
SQLException result set was a currency
Returns true if a write
public abstract boolean
operation in the specified
isDefinitelyWritable(int
column can be done for
column) throws SQLException
certain
203
public abstract int
Returns true if the specified
isNullable(int column) throws
column accepts NULL entries
SQLException
public abstract boolean
Returns true if the specified
isReadOnly(int column)
column is read only
throws SQLException
public abstract boolean Returns true if the WHERE
isSearchable(int column) clause can be a part of the
throws SQLException SQL query performed on the
specified column
public abstract boolean Returns true if the data
isSigned(int column) throws contained in the specified
SQLException column in the result set is
signed, if applicable
public abstract boolean
Returns true if a write on the
isWritable(int column) throws
specified column is possible
SQLException
Variables
Variable Name Additional Description
public final static int
NULL values not allowed
columnNoNulls
public final static int
NULL values allowed
columnNullable
public final static int NULL values may or may not
columnNullableUnknown be allowed, uncertain
public interface Statement
This class is used to execute a SQL query against the database via the Connection object.
The Connection.createStatement returns a Statement object. Methods in the Statement
class produce ResultSet objects which are used to fetch the result of a query executed in
this class.
Methods
Method Name Additional Description
public abstract void cancel() If a query is running in
throws SQLException another thread, a foreign
thread can cancel it by calling
this method on the local
Statement objects
204
instantiation
public abstract void Clears the warnings for the
clearWarnings() throws Statement
SQLException
Closes the Statement and
public abstract void close()
frees its associated resources,
throws SQLException
including any ResultSets
public abstract boolean Executes the parameter sql,
execute(String sql) throws which is an SQL query; this
SQLException method accounts for multiple
ResultSets
public abstract ResultSet Executes a query that returns
executeQuery(String sql) a ResultSet object (produces
throws SQLException some results) using the sql
parameter as the SQL query
public abstract int Executes a query that does
executeUpdate(String sql) not produce a resulting table;
throws SQLException the method returns the
number of rows affected or 0
if no result is produced
public abstract int Returns the maximum amount
getMaxFieldSize() throws of data returned for a
SQLException resulting column; applies only
to the following SQL
datatypes: BINARY,
VARBINARY,
LONGVARBINARY, CHAR,
VARCHAR, and LONGVARCHAR
public abstract int Returns the maximum number
getMaxRows() throws of rows a ResultSet can
SQLException contain
public abstract boolean Returns true if the next
getMoreResults() throws ResultSet of the query is
SQLException present, and moves the
ResultSet into the current
result space
Returns the number of
public abstract int
seconds that the JDBC driver
getQueryTimeout() throws
will wait for a query to
SQLException
execute
205
public abstract ResultSet Returns a ResultSet object
getResultSet() throws that is the current result of
SQLException the query; only one of these
is returned if only one
ResultSet is the result of the
query; if more ResultSets are
present, the getMoreResults
method is used to move to
the next ResultSet
public abstract int Returns the update count; if
getUpdateCount() throws the result is a ResultSet, -1 is
SQLException returned
public abstract SQLWarning Returns the warnings
getWarnings() throws encountered for the query of
SQLException this Statement object
public abstract void Sets the name of a cursor for
setCursorName(String name) future reference, and uses it
throws SQLException in update statements
public abstract void Sets escape substitution
setEscapeProcessing(boolean processing
enable) throws SQLException
public abstract void Sets the maximum amount of
setMaxFieldSize(int max) data that can be returned for
throws SQLException a column of type BINARY,
VARBINARY,
LONGVARBINARY, CHAR,
VARCHAR, and LONGVARCHAR
public abstract void Sets the maximum number of
setMaxRows(int max) throws rows that can be retrieved in
SQLException a ResultSet
public abstract void
Sets the time a driver will
setQueryTimeout(int seconds)
wait for a query to execute
throws SQLException
Exceptions
Finally, we get to the exceptions. As with the other sections, the exception listings
include a description and the class constructors and methods.
public class DataTruncation
This class extends SQLWarning. An exception is produced when data transfer is
prematurely terminated on a write operation, and a warning is generated when data
206
transfer is prematurely terminated on a read operation. You can use the methods
contained here to provide debugging information because the JDBC driver should throw
this exception when a data transfer problem is encountered.
Constructors
Constructor Additional Description
public DataTruncation(int Builds a Throwable
index, boolean parameter, DataTruncation object with
boolean read, int dataSize, int the specified properties
transferSize)
Methods
Method Name Additional Description
public int getDataSize() Returns the number of bytes
that should have been
transferred
public int getIndex() Returns the index of the
column or parameter that was
interrupted
public boolean getParameter() Returns true if the truncated
value was a parameter, or
false if it was a column
public boolean getRead() Returns true if truncation
occurred on a read; false
means truncation occurred on
a write
public int getTransferSize() Returns the number of bytes
actually transferred
public class SQLException
This class extends java.lang.Exception. It is the responsibility of the JDBC driver to
throw this class when a problem occurs during an operation.
Constructors
These constructors are used to create an SQLException with the specified information. It
is normally not necessary to create an exception unless the developer is working on
creating a driver or higher level JDBC interface:
public SQLException()
public SQLException(String problem)
public SQLException(String problem, String SQLState)
207
public SQLException(String problem, String SQLState,
int vendorCode)
Methods
Method Name Additional Description
public int getErrorCode() Returns the error code that
was part of the thrown
exception
public SQLException Returns the next exception as
getNextException() an SQLException object
public String getSQLState() Returns the SQL state that
was part of the thrown
exception
public synchronized void Sets the next exception as
setNextException excp for the SQLException
(SQLException excp) object
public class SQLWarning
This class extends SQLException. It is the responsibility of the JDBC driver to throw
this class when a problem occurs during an operation.
Constructors
These constructors build an SQLWarning object with the specified information. It is
normally not necessary to create an SQLWarning unless the developer is working on
creating a driver or higher level JDBC interface:
public SQLWarning()
public SQLWarning(String problem)
public SQLWarning(String problem, String SQLstate)
public SQLWarning(String problem, String SQLstate, int
vendorCode)
Methods
Method Name Additional Description
public SQLWarning Returns an SQLWarning
getNextWarning() object that contains the next
warning
public void Sets the next SQLWarning
setNextWarning(SQLWarning warning warn for the
warn) SQLWarning object
208