Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
778
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

108Chapter 3 JDBC API and JDBC Drivers

2.rowChanged event : Generated when a new row is inserted, updated, or deleted from the row set.

3.rowsetChanged event : Generated when the whole row set is created or changed.

In this book, the NetBeans IDE 6.8 is used, and the event-listener model has been set up by NetBeans IDE. So we can skip this step and do not need to take care of this issue during our coding process in the following chapters.

Step 3 allows users to set up all static or dynamic parameters for the query statement of the RowSet object. Depending on the data type of the parameters used in the query statement, suitable setXXX() methods should be used to perform this parameter setup process.

The fourth step is used to retrieve each row from the ResultSet object.

3.6 CHAPTER SUMMARY

This chapter discusses the fundamentals of JDBC and JDBC API, which include an overview of the JDBC and JDBC API, JDBC drivers and related components used in JDBC API.

The JDBC components and architecture are discussed and analyzed in detailed in the first part of this chapter. All classes and interfaces defined in a JDBC API are discussed and presented with a sequence tables. With some basic idea on JDBC and its components, the function and operational procedure of using JDBC API to perform data actions are described by three key steps:

1.Establish a connection between your Java application and related databases.

2.Build and execute SQL statements.

3.Process the results.

To setup a valid database connection, two popular connection methods are introduced: using the DriverManager class method and using the DataSource object. Relatively speaking, the second method is simple and easy to be used in real applications, since no detailed data source information is needed for this database connection.

To build and execute a typical SQL statement, the Statement, PreparedStatement, andCallableStatementcomponentsarediscussedandintroduced.BothPreparedStatement and CallableStatement classes are subclasses of the Statement class; however, both of them have more flexibility compared with the Statement component.

To process returned query results, different objects, such as ResultSet and RowSet, are introduced and discussed to provide users a clear picture about those objects and their functionalities.

Following the JDBC API and JDBC driver discussion, a detailed discussion about the types of JDBC Drivers is provided. Four popular types of drivers are analyzed and compared with architectures and their implementations.

Finally, four important components defined in the JDBC Standard Extension API, DataSource, Connection Pooling, Distributed Transactions, and RowSet are introduced and discussed with example coding.

The topics discussed in this chapter are prerequisite for the next chapter, and some components will be discussed and analyzed in more detailed to give users a deeper understanding and a better picture about their roles in real Java database applications.

Homework 109

HOMEWORK

I. True/False Selections

____1. JDBC is a standard Java Database Connectivity, and JDBC API can be considered as a Java Database Connectivity Application Programming Interface.

____2. JDBC API is not the only component included in a JDBC.

____3. JDBC API is composed of a set of classes and interfaces used to interact with databases from Java applications.

____4. JDBC Drivers are implementation dependent, which means that different applications need different drivers.

____5. The core of JDBC 2.0 API provides standard JDBC components that are located at the java.sql package, and some additional components such as JNDI and JTS are defined in JDBC 2.0 Standard Extension that is located at the javax.sql package.

____6. One can establish a database connection by directly calling the Driver class method connect().

____7. To load and register a JDBC driver, two popular methods can be used: using either Class. forName() method or to create a new instance of the Driver class.

____8. Three components can be used to build a SQL statement: Statement, Prepared-Statement, and CallableStatement.

____9. To pick up the execution results, one can use the executeQuery() and executeUpdate() methods. The former returns an integer and the latter returns a ResultSet.

___10. There are four types of JDBC drivers, and Type IV driver is a pure Java driver with fast running speed and high efficiency in data actions.

II. Multiple Choices

1.Generally, the JDBC API perform the following three functions _____

a.Connect to database, load JDBC driver, perform the query

b.Perform the query, connect to database, load JDBC driver

c.Get result from ResultSet, connect to database, load JDBC driver

d.Establish a connection to database, execute SQL statements, and get running results

2.To establish a connection with a DataSource object, you need to ________

a.Create a DataSource object, set properties and use this object

b.Set properties, setup a connection, and perform queries

c.Create a DataSource object, set properties, and register it with JNDI naming service

d.Register a DataSource object, set properties, and create a DataSource object

3.To build and run a SQL statement, following components can be utilized ______

a.Statement

b.Statement, PreparedStatement

c.Statement, PreparedStatement, CallableStatement

d.None of them

4.To execute a SQL statement to get a query result, _________ method(s) should be used.

a.executeQuery()

b.executeUpdate()

110 Chapter 3 JDBC API and JDBC Drivers

c.execute() and executeUpdate()

d.executeQuery() and execute()

5.To perform an insert, update or delete operation, the ________ method(s) should be used.

a.executeUpdate()

b.executeQuery()

c.executeQuery() and execute()

d.executeQuery() and executeUpdate()

6.The ________ method can be used to either pick up a query result or update a datum.

a.executeUpdate()

b.execute()

c.executeQuery()

d.None of them

7.A distributed transaction is defined as to access _________ data source(s) at _______ location(s).

a.Single, single

b.Multiple, same

c.Multiple, different

d.Single, multiple

8.The execute() method can _____________.

a.Not return any result

b.Return some results

c.Be used either to return a result or not return any result

d.None of above

9.A CachedRowSet class is a __________ that caches its data in __________.

a.Connected RowSet, database

b.Disconnected RowSet, database

c.Connected RowSet, memory

d.Disconnected RowSet, memory

10.The ResultSet object can be created by either executing the ___________ or __________ method, which means that the ResultSet instance cannot be created or used without executing a query operation first.

a.executeQuery(), getResultSet()

b.getResultSet(), execute()

c.createResultSet(), getResultSet()

d.buildResultSet(), executeQuery()

III. Exercises

1.Provide a detailed description about the JDBC API, which includes:

a.The definition of the JDBC and JDBC API

b.The components defined in a JDBC API, including all classes and interfaces

c.The architecture of the JDBC API

d.The regular functions of a JDBC API performed

e.The packages of the JDBC API is involved

Homework 111

2.Provide a brief discussion about database connection using JDBC API, which includes:

a.Two popular methods used to establish a connection

b.Operational procedure to establish a connection

c.How to use a DataSource object to establish a connection

d.Compare two popular method with the DataSource method in establishing a database connection

3.Explain the function of three different statement execution methods: executeQuery(), executeUpdate(), and execute(). For each method, provides a way to retrieve the execution result.

4.Provides a brief introduction about four types of JDBC drivers and their architecture.

5.Provides a brief introduction about the connection pooling API.

Chapter 4

JDBC Application Design

Considerations

This chapter discusses the application fundamentals of JDBC and JDBC API, which include the application models and operational procedures of the JDBC API implemented in Java database applications.

4.1 JDBC APPLICATION MODELS

JDBC API supports both two-tier and three-tier models for database accesses. In a twotier model, a Java application or an applet can communicate directly with the database.

In a three-tier model, commands are sent to a middle-tier, which sends the messages to the database. In return, the result of the database query is sent to the middle tier that finally directs it to the application or applet. The presence of a middle tier has a number of advantages, such as a tight control over changes done to the database.

4.1.1 Two-Tier Client-Server Model

In a two-tier client–server model, a Java application can directly communicate with the database. In fact, the so-called two-tier model means that the Java application and the target database can be installed in two components with two layers:

Application layer, which includes the JDBC driver, user interface, and the whole Java application, installed in a client machine.

Database layer, which includes the RDBMS and the database, installed in a database server.

Figure 4.1 shows a typical configuration of a two-tier model.

It can be found from Figure 4.1 that both Java application and JDBC API are located at the first layer, or the client machine and the DBMS and database are located at the second layer or the database server. A DBMS-Related protocol is used as a tool to communicate between these two layers. The interface to the database is handled by a JDBC driver that is matched to the particular database management system being used. The JDBC driver has double-side functionality; it passes SQL statement to the database when

Practical Database Programming with Java, First Edition. Ying Bai.

© 2011 the Institute of Electrical and Electronics Engineers, Inc. Published 2011 by John Wiley & Sons, Inc.

113

114 Chapter 4 JDBC Application Design Considerations

Java Application

Client Machine

JDBC API

DBMS-Related Protocol

 

 

 

 

 

 

DBMS &

Database Server

 

 

Database

 

 

 

 

 

 

 

 

 

 

 

Figure 4.1. A typical configuration of a two-tier model.

a data action request is sent from the client, and returns the results of executing those statements to the client when the data action is done.

A client–server configuration is a special case of the two-tier model, where the database is located on another machine called the database server. The Java application program runs on the client machine that is connected to the database server through a network.

Most topics discussed in Chapters 6–8 in this book are about two-tier model applications. The Java application projects are built in the client machine and communicate with the database server through the network to perform all kinds of data actions.The inherent flexibility of Java JDBC approach to develop database applications enables you to access a variety of RDBMS systems, including Microsoft Access 2007, SQL Server, and Oracle.

4.1.2 Three-Tier Client–Server Model

In a three-tier client-server model, a data action request is coming from an application GUI and sent to the application server that can be considered as a middle tier, and the application server that contains the JDBC API then sends SQL statements to the database located on a database server. When the data action is processed, the database sends the results back to the application server, which then sends them to the client. In fact, the so-called three-tier model is common in Web applications, in which the client tier is implemented in a Web browser, the middle tier is a Web server, and the database management system runs on a database server. This model can be represented by the following three layers:

Client layer, which includes a Web browser with some language-specified virtual machines, installed in a client machine.

Application server layer, which includes Java Web applications or Java Web services, installed in a Web server. This layer is used to handle the business logic or application logic. This may be implemented using Java Servlet engines, Java Server Pages, or Java Server Faces. The JDBC driver is also located in this layer.

Database layer, which includes the RDBMS and the database, installed in a database server.

Figure 4.2 shows a typical configuration of a three-tier model.

Advantages of using a three-tier configuration over two-tier counterpart include:

4.2 JDBC Applications Fundamentals 115

 

 

 

 

Java Application

Client Machine

 

or HTML Browser

 

(GUI)

 

 

 

HTTP or RMI Calls

Application Server

Web Server

JDBC API

DBMS-Related Protocol

 

 

 

 

DBMS &

Database Server

 

Database

 

 

 

 

 

 

 

 

Figure 4.2. A typical configuration of a three-tier model.

Application performance can be greatly improved by separating the application server and database server.

Business logic is clearly separated from the database.

Client application can then use a simple protocol to access the server.

Topics discussed in Chapters 8 and 9 in this book are about three-tier applications that use a Web browser as the client, a Java Server Face (JSF) or Java Server Page (JSP) as the middle tier, and a relational database management system as the database server.

Now that we have a clear picture about the Java application running models, next we need to dig a little deeper about the Java database applications.

4.2 JDBC APPLICATIONS FUNDAMENTALS

As we discussed in Section 3.1 in Chapter 3, to run a Java database application to perform data actions against the selected database, a JDBC API needs to perform the following operations:

1.Establish a connection between your Java application and related databases.

2.Build and execute SQL statements.

3.Process the results.

In fact, to successfully develop and run a Java database application, the above three operational steps need to be further divided into the following seven steps:

1.Import necessary Java packages, such as java.awt, java.util, javax.swing, java.sql, and javax.sql.

2.Load and register the JDBC driver.

3.Establish a connection to the database server.

4.Create a SQL statement.

5.Execute the built statement.

116Chapter 4 JDBC Application Design Considerations

6.Retrieve the executing results.

7.Close the statement and connection objects.

In all steps listed above, step 1 is a prerequisite step since all JDBC-related components and interfaces are defined in the java.sql and javax.sql packages. All GUIrelated components are defined in the java.awt and javax.swing packages, and all other application-related components are defined in the java.util package. In order to use any component defined in those packages, you must first import those packages into your program to provide namespaces and locations for those components. Otherwise, a compiling error may be encountered, since the compiler cannot find and identify those components when you used them but without providing the related packages.

In this and the following sections, we will provide a deeper and more detailed discussion about the data actions on Java database applications based on these seven fundamental steps.

4.2.1 Loading and Registering Drivers

As we studied in Chapter 3, to establish a valid database connection, first you need to load and register a JDBC driver. Then you can call the connect() method to establish a database connection to your desired database.

We provided a brief discussion about the JDBC Driver and DriverManager components in Chapter 3. In fact, the core of the JDBC API is the JDBC Driver that can be accessed and called from the DriverManager class method. However, the Driver class in under the control of the DriverManager class, and the DriverManager is exactly a manager for the Driver class. When using this Driver class, you cannot call and run any method defined in the Driver class; instead, you need to call them via the DriverManager class methods.

The DriverManager class is a set of utility functions that work with the Driver methods together and manage multiple JDBC drivers by keeping them as a list of drivers loaded. Although loading a driver and registering a driver are two steps, only one method call is necessary to perform these two operations. The operational sequence of loading and registering a JDBC driver is:

1.Call class methods in the DriverManager class to load the driver into the Java interpreter.

2.Register the driver using the registerDriver() method.

When loaded, the driver will execute the DriverManager.registerDriver() method to register itself. The above two operations will never be performed until a method in the DriverManager is executed, which means that even both operations have been coded in an application; however, the driver cannot be loaded and registered until a method such as connect() is first executed.

To load and register a JDBC driver, two popular methods can be used;

1.Use Class.forName() method:

Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);

2.Create a new instance of the Driver class:

Driver sqlDriver = new com.microsoft.sqlserver.jdbc.SQLServerDriver;

4.2 JDBC Applications Fundamentals 117

import java.sql.*; try

{

//Load and register SQL Server driver Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

}

catch (Exception e) {

System.out.println("Class not found exception!" + e.getMessage());

}

Figure 4.3. A sample coding for the driver loading and registering.

Relatively speaking, the first method is more professional since the driver is both loaded and registered when a valid method in the DriverManager class is executed. The second method cannot guarantee that the driver has been registered by using the DriverManager.

A piece of sample codes that are used to load and register a Microsoft SQL Server JDBC driver using the first method is shown in Figure 4.3.

In Figure 4.3, the first coding line is used to import the JDBC API package java.sql.*. Then a try…..catch block is used to load and register a Microsoft SQL Server JDBC Driver. The Class.forName() method is utilized to make sure that our JDBC Driver is not only loaded, but also registered when it is connected by running the getConnection() method later.The argument of this method,com.microsoft.sqlserver. jdbc.SQLServerDriver, is the name of this Microsoft SQL Server JDBC Driver class, and it is created by the NetBeans when it is added to a Java database application project. The catch block is used to track any possible error for this loading and registering.

The related exception information will be displayed if any error occurred.

You can use the second method to replace this method to perform the same driver loading and registering operation if you like.

4.2.2 Getting Connected

To establish a connection to the desired database, two methods can be used:

1.Using DriverManager.getConnection() method

2.Using Driver.connect() method

Before we can take a closer look at these two methods, first, let’s have a quick review for all methods defined in these two classes, DriverManager and Driver.

4.2.2.1 The DriverManager and Driver Classes

All 12 methods defined in the DriverManager class are shown in Table 4.1.

Four methods in the DriverManager class are widely applied in most database applications; getConnection(), getDriver(), registerDriver(), and deregisterDriver(). Note that the getConnection() method has two more overloading methods with different arguments.

118 Chapter 4 JDBC Application Design Considerations

Table 4.1. Methods defined in the DriverManager class

Method

Function

 

 

deregisterDriver(Driver dr)

Remove a Driver from the driver list

getConnection(String url,

Attempt to establish a connection to the referenced database

Properties login)

 

getConnection(String url, String

Attempt to establish a connection to the referenced database

user, String pswd)

 

getConnection(String url)

Attempt to establish a connection to the referenced database

getDriver(String url)

Locate an appropriate driver for the referenced URL from

 

the driver list

getDrivers()

Get a list of all drivers currently loaded and registered

getLoginTimeout()

Get the maximum time (in seconds) a driver will wait for a

 

connection

getLogStream()

Get the current PrintStream being used by the

 

DriverManager.

Println(String msg)

Print a message to the current LogStream.

registerDriver(Driver dr)

Add the driver to the driver list. This is normally done

 

automatically when the driver is instantiated

setLoginTimeout(int seconds)

Set the maximum time (in seconds) that a driver can wait

 

when attempting to connect to a database before giving up

setLogStream(PrintStream out)

Set the PrintStream to direct logging message to

 

Table 4.2. Methods defined in the Driver class

 

 

Method

Function

 

 

acceptsURL(String url)

Return a true if the driver is able to open a connection to the

 

database given by the URL

connect(String url, Properties

Check the syntax of the URL and the matched drivers in the

login)

driver list. Attempt to make a database connection to the

 

given URL

getMajorVersion()

Determine the minor revision number of the driver

getMinorVersion()

Determine the major revision number of the driver

getPropertyInfo(String url,

Return an array of DriverPropertyInfo objects describing login

Properties login)

properties accepted by the database

jdbcCompliant()

Determine if the driver is JDBC COMPLIANT

 

 

All six methods defined in the Driver class are shown in Table 4.2.

Most popular methods in the Driver class are acceptsURL() and connect().

Most methods defined in the Driver class will not be called directly in most Java database applications, instead, they will be called indirectly by using the DriverManager class.

Now let’s have a closer look at these two methods.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]