Using JDBC M eta D ata Interfaces

Một phần của tài liệu practical database aprogramming with java (Trang 167 - 171)

PART II Building Three-Tier Client–Server Applications 555 Chapter 8 Developing Java Web Applications to Access Databases 557

4.2.5 Using JDBC M eta D ata Interfaces

In addition to general and popular data information provided by three statement inter- faces and execution methods, JDBC also provides useful and critical information and descriptions about the database, running result set and parameters related to the JDBC drivers and database applications. All of these properties, structures and descriptions can be categorized into three interfaces of so - called metadata interfaces, or

1. ResultSetMetaData interface 2. DatabaseMetaData interface 3. ParameterMetaData interface

In the following sections, we will concentrate on these three interfaces to illustrate how to use these interfaces to retrieve detailed descriptions and structures, as well as properties related to the data action components, such as ResultSet , database, and parameters to facilitate database applications.

Let ’ s start from the ResultSetMetaData interface.

4.2.5.1 Using the R esult S et M eta D ata Interface

In Section 4.2.4 , we discussed how to retrieve running result stored in a ResultSet object and important methods of this interface. By using different fetching methods, either fetch- ing by rows or columns, we can easily retrieve a whole set of returned results stored in a

Table 4.10. Methods defi ned in the ResultSetMetaData interface

Method Function

getCatalogName(int index) Determine the name of the catalog that contains the referenced column

getColumnCount() Return the total number of columns contained in the ResultSet object

getColumnDisplaySize(int index) Return the maximum display width for the selected column getColumnLabel(int index) Return the preferred display name for the selected column getColumnName(int index) Return the name of the column for the selected column getColumnType(int index) Return the SQL data type for the selected column getPrecision(int index) Return the precision used for the selected column getScale(int index) Return the scale used for the selected column

getSchemaName(int index) Return the name of the schema that contains the selected column

getTableName(int index) Return the name of the table that contains the selected column

isAutoIncrement(int index) Determine if the column is automatically numbered by the database (autonumber)

isCurrency(int index) Determine if the column represents currency isNullable(int index) Determine if the column is able to accept null values isSigned(int index) Determine if the column contains signed numbers isWritable(int index) Determine if the column is writable by the user isReadOnly(int index) Determine if the column is read - only

ResultSet object. However, in some applications, we may need more detailed informa- tion and properties about the returned result set, such as the total number of columns returned, each column name and data type, as well as some other structure information related to the returned result set. By using these structure information and properties, we can get a clear and full picture about the returned ResultSet , and furthermore enable us to retrieve our desired data information more directly and conveniently. With the help of the metadata provided by the ResultSetMetaData , you can develop entire database applications without even knowing what RDBMS, table, or type of data to be accessed.

The ResultSetMetaData interface provides a collection of information about the structure and properties related to the returned ResultSet object, and this give us a possibility to perform the functions we described above.

The ResultSetMetaData interface contains more than 20 methods, and Table 4.10 shows 16 most popular methods.

It can be found from Table 4.10 that the top 10 methods in a ResultSetMetaData object are mainly used to retrieve the structure and properties for the specifi ed column with the column index as an argument. The rest of methods that return a Boolean value are used to determine some important properties that describe special functions provided by the database engine for the selected column. One of the advantages of using this metadata is that you can build dynamic applications that are independent of the data source. One possible way to achieve this is to remove the need for all direct column name references.

c04.indd 146

c04.indd 146 7/20/2011 2:11:53 PM7/20/2011 2:11:53 PM

www.traintelco.com

Because of the space limitation, we can only provide a brief discussion for some important methods that are widely implemented in most database applications.

After a data query is executed and a ResultSet object is returned, before we can retrieve our desired data from the ResultSet , we may need to get some structure infor- mation and properties related to columns we preferred. One of the most important properties is the total number of columns returned in the ResultSet object. By using the getColumnCount() method, we can get not only the total number of columns, but also the content of each column easily. Figure 4.17 shows a piece of example codes to illustrate how to use this method to scan the entire ResultSet to retrieve each column from it.

The fi rst coding line is used to create a ResultSet object by executing the execute- Query() method. Then a ResultSetMetaData object rsmd is created by calling the

getMetaData() method defi ned by the ResultSet interface. To pick up each returned column, a while loop is used combined with the next() method. By using this piece of codes, you even do not need to know how many columns returned in that ResultSet , and what are the names for each column; in other words, you do not have to have prior knowledge about the table and database — you can retrieve all columns with their exact names! Yes, that is easy and fancy.

In some applications, you may need to know some other useful information about the columns, such as the data type of each column, the width of each column, the preci- sion and scale of the selected column if a fl oating point or double data is stored in that column. To get those properties, you can call the appropriate methods, such as get- ColumnType() , getColumn - DisplaySize() , getPrecision() and getScale() .

Besides to get some important information and properties about the returned ResultSet, sometimes, we may need to get similar information for the connected database.

In that case, you may need to use the DatabaseMetaData interface.

4.2.5.2 Using the D atabase M eta D ata Interface

Compared with other metadata interfaces, the DatabaseMetaData is the largest meta- data interface, with over 150 methods. This interface is mainly used for by those developers who are building database applications that need to be fully RDBMS independent, which means that the developers do not need to know anything about the database or do not have prior knowledge about the database they are using. In this way, the users can discover and retrieve structures and properties of the RDBMS dynamically as the application runs.

Figure 4.17. An example coding of using the getColumnCount() method.

ResultSet rs = pstmt.executeQuery();

ResultSetMetaData rsmd = rs.getMetaData();

While (rs.next()){

for (int m = 1; m< rsmd.getColumnCount(); m ++) {

System.out.println( rs.getString(m));

} }

Table 4.11. Popular methods defi ned in the DatabaseMetaData interface

Method Function

getCatalogs() Return a ResultSet containing a list of all catalogs available in the database

getCatalogTerm() Determine what the database specifi c name for Catalog is getDatabaseProductName() Return the name of the database product

getDatabaseProductVersion() Return the database revision number getDriverName() Return the name of the driver

getDriverVersion() Return the revision number of the driver getPrimaryKeys(String catalog,

String schema, String table)

Return a ResultSet describing all of the primary keys within a table

getProcedures(string catalog, String schPatt, String proPatt)

Return a ResultSet describing all stored procedures available in the catalog

getProcedureTerm() Determine the database specifi c term for procedure

getSchemas() Return a ResultSet containing a list of all schemas available in the database

getSchemaTerm() Determine the database specifi c term for schema getTables(String catalog, String

schePatt, String tablePatt, String[] types)

Return a ResultSet containing a list of all tables available matching the catalog, schema, and table type selection criteria

getTableTypes() Return a ResultSet listing the table types available

getTypeInfo() Return a ResultSet describing all of the standard SQL types supported by the database

getURL() Return the current URL for the database

getUserName() Return the current user name used by the database

To create a DatabaseMetaData object, one needs to call the getMetaData() method defi ned in the Connection interface.

Relatively speaking, the ResultSetMetaData interface allows you to discover the structure of tables and properties of columns, but the DatabaseMetaData interface enables you to dynamically determine properties of the RDBMS. Table 4.11 shows some 16 most popular and important methods widely implemented by the DatabaseMetaData interface.

These 16 methods can be divided into seven groups based on their functionalities:

1. Catalog Identifi cation Methods 2. Database Identifi cation Methods 3. Driver Identifi cation Methods 4. Stored Procedure - Related Methods 5. Schema Identifi cation Methods 6. Table Identifi cation Methods

7. Database - Related Parameters Methods

To get the name and version of the current database being used, the

getDatabaseProduct - Name() and getDatabaseProductVersion() methods can

c04.indd 148

c04.indd 148 7/20/2011 2:11:53 PM7/20/2011 2:11:53 PM

www.traintelco.com

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 P arameter M eta D ata Interface

The detailed information about the parameters passed into or from the database can be obtained by calling the getParameterMetaData() method that is defi ned 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 defi ned 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 fi elds 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.

Một phần của tài liệu practical database aprogramming with java (Trang 167 - 171)

Tải bản đầy đủ (PDF)

(791 trang)