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

Practical Database Programming With Java

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

4.2 JDBC Applications Fundamentals 149

be used. Similarly, to get the name and revision number of the JDBC driver being used, the getDriverName() and getDriverVersion() methods can be executed.

In fact, the DatabaseMetaData interface provides methods that allow you to dynamically discover properties of a database as the project runs. Many methods in the

DatabaseMetaData return information in the ResultSet component, and one can get those pieces of information from ResultSet object by calling related methods, such as getString(), getInt(), and getXXX().A SQLException would be thrown out if the queried item is not available in the MetaData interface.

Overall, the DatabaseMetaData interface provides an easy and convenient way to allow users to identify and retrieve important structure and properties information about the database dynamically.

4.2.5.3 Using the ParameterMetaData Interface

The detailed information about the parameters passed into or from the database can be obtained by calling the getParameterMetaData()method that is defined in the PreparedStatement interface. Although this interface is not as popular as ResultSetMetaData and DatabaseMetaData, it is useful in some special applications.

Basically, the ParameterMetaData interface can be defined as: an object that can be used to get information about the types and properties of the parameters in a PreparedStatement object. For some queries and driver implementations, the data that would be returned by a ParameterMetaData object may not be available until the PreparedStatement has been executed. Some driver implementations may not be able to provide information about the types and properties for each parameter marker in a CallableStatement object.

The ParameterMetaData interface contains seven fields and nine methods. Table 4.12 shows some most popular methods that are widely implemented in most database applications.

Figure 4.18 shows a piece of example codes to illustrate how to retrieve the total number of parameters related to a PreparedStatement object.

After a PreparedStatement instance is created, the getParameterMetaData() method is executed to retrieve the total number of parameters returned in the

ParameterMetaData object.

Finally, let’s handle the closing the connection object and releasing used resources, including the statement objects.

4.2.6 Closing the Connection and Statements

After a set of data actions has been performed and the desired data have been acquired, the Connection object that is used to connect to our target database should be closed, and the related data operational resources including all opened statement objects used for these data actions should also be released. Otherwise, you may encounter some possible exceptions when you try to open a database that has been opened but without being closed in the previous applications. To these cleanup jobs, it is very easy with a piece of codes shown in Figure 4.19.

150 Chapter 4 JDBC Application Design Considerations

Table 4.12. Popular methods defined in the ParameterMetaData interface

Method

Function

 

 

getParameterCount()

Return the number of parameters in the

 

PreparedStatement object for which this

 

ParameterMetaData object contains information

getPrecision(int param)

Return the designated parameter’s number of decimal

 

digits

getScale(int param)

Return the designated parameter’s number of digits to

 

right of the decimal point

getParameterType(int param)

Return the designated parameter’s SQL type

getParameterTypeName(int param)

Return the designated parameter’s database-specific type

 

name

getParameterMode(int param)

Return the designated parameter’s mode

isNullable(int param)

Determine whether null values are allowed in the

 

designated parameter

isSigned(int param)

Determine whether values for the designated parameter

 

can be signed numbers

 

 

String query = "SELECT user_name, pass_word FROM LogIn " + "WHERE user_name = ? AND pass_word = ?";

PreparedStatement pstmt = con.prepareStatement(query);

pstmt.setString(1, “cse”); pstmt.setString(2, “mack8000”);

ResultSet rs = pstmt.executeQuery();

ParameterMetaData pmmd = pstmt.getParameterMetaData();

System.out.println( “The total number of parameter is “ + pmmd.getParameterCount());

Figure 4.18. An example coding of using the getParameterCount() method.

try{

stmt.close();

if (!con.isClosed()) con.close();

}

catch(SQLException e){

System.out.println("Could not close!" + e.getMessage());

}

Figure 4.19. An example coding of closing the Connection and Statement objects.

4.3 Chapter Summary 151

To do a closing operation, a try…catch block had better be used to track and monitor this closing process with possible exceptions warning.

4.3 CHAPTER SUMMARY

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, are discussed in detailed in this chapter.

Starting with an introduction to two JDBC application models, two-tier and three-tier models, a detailed illustration and description about these two models are given in the

first part of this chapter. A typical two-tier model contains an application server and a database server, in which a Java database application project residents in an application server, and the target database is located at the database server. The so-called three-tier model places the application onto an application server that can be considered as a midtier, and installs database in a database server. To run this three-tier model application, the user needs to communicate with the application server by using a Web browser that can be considered as a top tier, with a GUI being installed in this browser. Then the application server can process requests sent from the browser via the target database via the database server. Finally, when requests have been done, results will be returned to the browser by the application server.

Following the application models, a complete operational procedure to perform a standard Java database application is discussed with some example codes, which includes:

Load and register a JDBC Driver.

Connect to the target database using either DriverManager.getConnection() method or Driver.connect()method.

Execute an SQL statement by creating and calling an appropriate Statement object, which include:

Statement object

PreparedStatement object

CallableStatement object

Distinguish different queries by running associated execute method.

Execute DDL and DML SQL statements.

Retrieve the running result by creating and getting a ResultSet object.

Develop sophisticated Java database applications using different JDBC metadata interfaces, including the ResultSetMetaData, DatabaseMetaData, and ParameterMetaData interfaces.

Close the connected database and opened statement objects to release data resource used for the application.

Combining the contents in this chapter and the last chapter, you should have had a complete and clear picture about the JDBC fundamentals and application procedure. Beginning from the next chapter, we will introduce and discuss some development tools and actual techniques used in Java database applications.

152 Chapter 4 JDBC Application Design Considerations

HOMEWORK

I. True/False Selections

____1. JDBC applications are made of two models: two-tier and three-tier models.

____2. In a three-tier model, the application is located at a Web server, and the database is installed in a database server. The user can access the application server through a Web browser with a GUI being installed in the browser.

____3. To load and register a driver, the creating a new instance of the Driver class method is a better method compared with the Class.forName() method.

____4. When establishing a database connection, the DriverManager.getConnection() method is a better method compared with the Driver.connect() method.

____5. A JDBC URL is composed of three parts: network host name, the database server name, and the port number.

____6. By using three methods defined in the Connection interface, createStatement(), prepareStatement(), and prepareCall(), one can create three statement objects:

 

Statement, PreparedStatement, and CallableStatement.

____7.

The Statement object can be used to perform both static and dynamic data queries.

____8.

To create a ResultSet object, you can use either the getResultSet() method or

 

call the executeQuery() method.

____9.

The executeQuery() method returns an integer that equals to the number of rows that

 

have been returned, and the executeUpdate() method returns a ResultSet object

 

containing the running result.

___10.

The next() method defined in the ResultSet interface can be used to move the cursor

 

that points to the current row to the next row in a ResultSet.

II. Multiple Choices

1.The __________ object provides methods for the creation of Statement objects that will be used to execute SQL statements in the next step.

a.Statement

b.Connection

c.DriverManager

d.Driver

2.The relationship between three statement objects are: the ____________ is a subclass of the

__________ that is a subclass of the __________.

a.CallableStatement, PreparedStatement, Statement

b.Statement, CallableStatement, PreparedStatement

c.PreparedStatement, Statement, CallableStatement

d.Statement, PreparedStatement, CallableStatement

3.The __________ method returns a(n) __________, and the _________ method returns a(n)

__________.

a.execute(), ResultSet, executeQuery(), integer

b.executeQuery(), integer, execute(), nothing

c.executeUpdate(), integer, executeQuery(), ResultSet

d.execute(), integer, executeUpdate(), ResultSet

Homework 153

4.The __________ object is used to execute a static SQL query, but the _________ object is used to execute a dynamic SQL query with IN and OUT parameters.

a.PreparedStatement, Statement

b.Statement, PreparedStatement

c.CallableStatement, Statement

d.Statement, CallableStatement

5.Both interfaces, PreparedStatement and CallableStatement, are used to perform dynamic SQL statements; however, the ________ performs queries with only _____ parameters, but the

_______ calls stored procedures with both ______ and _______ parameters.

a.CallableStatement, OUT, PreparedStatement, IN, OUT

b.PreparedStatement, IN, CallableStatement, IN, OUT

c.CallableStatement, IN, PreparedStatement, IN, OUT

d.PreparedStatement, OUT, CallableStatement, IN, OUT

6.By using __________ method, we can get a collection of information about the structure and properties of the returned ResultSet object.

a.getResultSetMetaData()

b.getResultSet()

c.getMetaData()

d.ResultSetMetaData()

7.To create a ____________ object, one needs to call the ___________ method defined in the Connection interface.

a.ResultSet, getMetaData()

b.Statement, getStatement()

c.PreparedStatement, getPreparedStatement()

d.DatabaseMetaData, getMetaData()

8.The ____________ interface allows you to discover the structure of tables and properties of columns, but the _______________ interface enables you to dynamically determine properties of the RDBMS.

a.ResultSet, DatabaseMetaData

b.ParameterMetaData, ResultMetaData

c.DatabaseMetaData, ParameterMetaData

d.DatabaseMetaData, ResultSet

9.When using a CallableStatement object to run a stored procedure, you need to register the

__________ parameters by using the _____________ method.

a.IN/OUT, getParameters()

b.IN, registerINParameter()

c.OUT, registerOUTParameter()

d.IN/OUT, registerINOUTParameter()

10.The placeholder used in the setXXX() and the registerOUTParameter() methods is used to ___________________.

a.Indicate the location of the input or output parameters

b.Reserve spaces for input or output parameters

c.Inform the compiler to hold memory spaces for those parameters

d.All of them

154 Chapter 4 JDBC Application Design Considerations

III. Exercises

1.Provide a brief description about seven basic steps to use JDBC.

2.Translate the above seven steps to Java codes.

3.Provide a detailed description about JDBC three-tier model and its function.

4.Provides a brief description about the JDBC URL.

5.Explain the operational sequence of retrieving results from a returned ResultSet object.

6. Explain the relationship between three Statement objects, and illustrate why and how the CallableStatement object can use setXXX() methods defined in the

PreparedStatement interface.

7. Explain the advantages of using JDBC metadata for Java database applications.

Chapter 5

Introduction to NetBeans IDE

Java was originally created by Sun Microsystems to try to overcome some complexities in C++ and try to simplify the structure and architecture of applications developed by using object-oriented programming (OOP) languages such as C++. In the early days, Java developers need to use separate tools to build, develop, and run a Java application. The following tools are most popular used when building a Java application:

NotePad or WordPad—used to develop the Java source codes

Java Compiler—used to compile the Java source codes to the Java byte codes

Java Interpreter—used to convert the byte codes to the machine codes

There is no any graphical user interface (GUI) tool available in the early days and developers have to use the Java layout manager to design and build the GUI by using different layouts with different components, such as buttons, labels, text fields, checkboxes, and radio buttons. Even Web-related Java applications, such as Applets, must be built by using different tools, too. This brought a significant inconvenience and complicated development environment for Java developers in that age.

As more sophisticated and advanced techniques were developed, the Java development environment and tools have been greatly improved. By combining Java Software

Development Kits (SDK) and GUI components, such as Abstract Windowing Toolkit

(AWT) and Swing API, Sun integrated those components and tools together to establish and build an Integrated Development Environment (IDE). This IDE is very similar to Visual Studio.NET, in which all program development tools and components have been integrated together and categorized into the different packages. Developers can design, develop, build, and run a Java standalone or a Web application easily and conveniently inside this IDE without needing to use different tools.

The NetBeans IDE is one of the most current and updated IDEs and widely implemented in a wide spectrum of Java applications. The NetBeans IDE is actually written in Java and runs everywhere a Java Virtual Machine (JVM) is installed, including Windows, Mac OS, Linux, and Solaris. A Java Development Kits (JDK) is required for

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.

155

156 Chapter 5 Introduction to NetBeans IDE

Java development functionality, but is not required for development in other programming languages.

The NetBeans project consists of an open-source IDE and an application platform that enable developers to rapidly create web, enterprise, desktop, and mobile applications using the Java platform, as well as JavaFX, PHP, JavaScript and Ajax, Ruby and Ruby on Rails, Groovy and Grails, and C/C++.

NetBeans IDE, which is released by Sun Microsystems, is a modular, standards-based integrated development environment (IDE) written in the Java programming language. The NetBeans project consists of a full-featured open source IDE written in the Java programming language and a rich client application platform, which can be used as a generic framework to build any kind of application.

5.1 OVERVIEW OF THE NETBEANS IDE 6.8

The current version of the NetBeans IDE is 6.8, and it is the first IDE to offer complete support for the entire Java Enterprise Edition (EE) 6 spec with improved support for JSF 2.0/Facelets, Java Persistence 2.0, Enterprise JavaBean (EJB) 3.1 including using EJBs in web applications, RESTful web services, and GlassFish v3. It is also recommended for developing with the latest JavaFX SDK 1.2.1, and for creating PHP web applications with the new PHP 5.3 release or with the Symfony Framework.

Table 5.1 shows some most popular features provided by NetBeans IDE 6.8.

Table 5.2 shows the most popular techniques supported by the NetBeans IDE 6.8 and application servers adopted by the NetBeans 6.8.

Table 5.1. Most popular features supported by NetBeans IDE 6.8

Project Category

Features

 

 

Java Enterprise Edition 6

• Web Projects with Java EE 6 and Java EE 6 Web profiles, EJBs

 

in web applications.

 

• EJB 3.1 support, EJB project file wizard also supports Singleton

 

session type.

 

• RESTful web services (JAX-RS 1.1), GlassFish Metro 2.0 web

 

services (JAX-WS 2.2), JAXB 2.2.

 

• Java Persistence JPA 2.0, deployment, debugging, and profiling

 

with GlassFish v3 application server.

Web Projects with

• Code completion, error hints, namespace completion,

JavaServer Faces 2.0

documentation pop-ups, and tag auto-import for Facelets.

(Facelets)

• Editor support for Facelets libraries, composite components,

 

expression language, including generators for JSF and HTML

 

forms.

 

• Customizable JSF components palette generates JSF forms and

 

JSF data tables from entities.

 

• New File wizard generates customizable CRUD (create/read/

 

update/delete) JSF pages from entities.

 

• Broader usage of annotations instead of deployment descriptors.

 

5.1 Overview of the NetBeans IDE 6.8 157

Table 5.1. (Continued)

 

 

 

Project Category

Features

 

 

JavaFX

• Added support for the latest JavaFX SDK 1.2.1.

 

• Improved code completion.

 

• Editor Hints: Fix Imports, Surround With, Implements Abstract

 

Methods, and more.

 

• Improved navigation: Hyperlinks, Go to Type, Find Usages.

http://Kenai.com:

• Full JIRA support (plug-in from update center).

Connected Developer

• Project dashboard with more member and project details,

 

improved search and navigation, easier project sharing.

 

• Improved instant messenger integration: Online presence,

 

private and group chat with Kenai members, easy to add links

 

to code/files/issues/stack traces to messages.

 

• Improved issue tracker integration.

PHP

• Full PHP 5.3 support: namespaces, lambda functions and

 

closures, syntax additions: NOWDOC, ternary conditions, jump

 

labels, __callStatic().

 

• Symfony Framework support: Symfony projects, Symfony

 

commands, shortcuts, PHP syntax coloring in YAML files.

 

• Create a PHP project from a remote PHP application.

 

• PHPUnit, Code Coverage, FTP/SFTP integration

 

improvements, exclude PHP project folders from scanning/

 

indexing.

Maven

• New Project from Maven archetype catalog and improved

 

support for Java EE 6, Groovy, Scala projects.

 

• Customizable dependency exclusion in dependency graph.

 

• Maven CheckStyle plug-in.

 

• “Update from Kenai” action for Kenai.com-hosted Maven

 

projects.

Ruby

• Support for creating Rails 2.3.4 apps with dispatchers, JRuby

 

1.4, Ruby 1.9 debugging, and RSpec 1.2.7

 

• Improved rename refactoring, type inference, and navigation

 

• Specifying arguments for Rails servers

 

• Run/Debug File with arguments, also for files not part of a

 

project

C and C++

• Profiling: New Microstate Accounting indicator, Thread

 

Map view, Hot Spots view, Memory Leaks view, Sync

 

Problems view

 

• Faster synchronization during remote development

 

• Support for gdbserver attach and easier attaching to already

 

running processes

Miscellaneous

• Java Debugger: Mark an object in the variables tree with a

Improvements

name to refer to it in expressions

 

• Database integration: Code completion in SQL Editor now also

 

for DELETE, DROP, UPDATE statements, and for reserved

 

keywords

 

• Groovy 1.6.4 & Grails: Improved code completion, including

 

methods introduced via AST Transformations

 

 

158 Chapter 5 Introduction to NetBeans IDE

Table 5.2. Most popular techniques and application servers supported by NetBeans 6.8

Category

Supported Techniques and Application Servers

 

 

Supported technologies

Java EE 5, Java EE 6 and J2EE 1.4

 

JavaFX SDK 1.2.1

 

Java ME SDK 3.0

 

Struts 1.3.8

 

Spring 2.5

 

Hibernate 3.2.5

 

Java API for RESTful Web Services (JAX-RS) 1.1

 

PHP 5.3, 5.2, 5.1

 

Ruby 1.9, 1.8

 

JRuby 1.4

 

Rails 2.3.4

 

Groovy 1.6.4

 

Grails 1.1

 

VCS

 

CVS: 1.11.x, 1.12.x

 

Subversion: 1.4.x, 1.5.x, 1.6.x

 

Mercurial: 1.x

 

• ClearCase V7.0

Tested application servers

• GlassFish v3

 

• Sun Java System Application Server PE 8.2

 

• WebLogic 11g (10.3.1.0)

• Tomcat 6.0.20

• Tomcat 5.5

• JBoss 5.0

As we know, the NetBeans projects are composed of an open-source IDE and an application platform that enable developers to rapidly create web, enterprise, desktop, and mobile applications. Let’s have a closer look at these two components to have a deeper understanding about this IDE.

5.1.1 The NetBeans Platform

The NetBeans Platform is a broad Swing-based framework on which you can base large desktop applications. The IDE itself is based on the NetBeans Platform. The Platform contains APIs that simplify the handling of windows, actions, files, and many other things typical in applications.

Each distinct feature in a NetBeans Platform application can be provided by a distinct

NetBeans module, which is comparable with a plug-in. A NetBeans module is a group of Java classes that provides an application with a specific feature.

You can also create new modules for NetBeans IDE itself. For example, you can write modules that make your favorite cutting-edge technologies available to users

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