Java Data Access—JDBC, JNDI, and JAXP phần 5 ppt

38 273 0
Java Data Access—JDBC, JNDI, and JAXP phần 5 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Structural information You can also use a DatabaseMetaData object to retrieve information on tables, stored procedures, referential integrity, and data types. These methods return ResultSet objects. Of course, the result sets differ depending upon the methods used to query the database. The number of columns ranges from 1 to 18, all of which may be of different data types. Most of the method calls are straightforward. However some, such as those that provide column information, enable you to supply string patterns as parameters to limit the number of rows returned. String patterns are essentially wildcard characters that enable you to narrow your search. You can use the underscore (_) character to match any single character or the percent symbol (%) to match zero or more characters. In general, you should use string patterns to limit the number of rows returned by certain DatabaseMetaData methods. For example, if you call the getColumns() method to retrieve a result set of information on a certain table’s columns, you may accidentally retrieve the column names for every column in all the database’s tables. In this instance the result set will contain not only the column information for the target table, but the system’s and user’s tables as well. The result sets in this case will be quite large and probably meaningless. String Patterns String patterns enable you to “filter” the number of rows a result set returns. You can only use string patterns in the DatabaseMetaData methods that support them. Two special characters, % and _, enable you to build string patterns. You use the % to match zero or more characters. For example, EM% will only allow the method to retrieve data that starts with the characters EM. The string pattern EM%S will retrieve data that starts with EM and ends with S. The data can contain any characters in between, and can be any number of characters in length. You can use the underscore to match a single character. EM_ will only retrieve data that starts with EM and ends with any character. In this case the name of the field you are matching will only be three characters long. The remainder of this section focuses on how to use the DatabaseMetaData object to retrieve information about tables, columns, data types, and referential integrity constraints. Although you can retrieve other information with the DatabaseMetaData object, I find this information most useful when I need to probe a database. Table and column metadata You can obtain details on all the tables and table columns for which you have access rights. This may include system and other user schemas as well as your own. As I mentioned before, if you do not use string patterns you may create a very large result set. The DatabaseMetaData methods getTables() and getColumns() retrieve information about the tables and table columns in a database, respectively. The method signatures are somewhat different from the usual Java methods because they can take string patterns as parameters. The following is the getTable() method definition: public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types); Think of these parameters as result set filters as each one can limit the number of rows returned. In the preceding getTables() method, the first parameter is the database catalog you wish to search for tables. A Chapter 8: Mining Database Metadata with JDBC 142 catalog is analogous to a namespace and is used to separate data structures. The next two parameters further filter the result set by enabling you to specify the schema and tables that you want to include in the result set. Notice that you can use string patterns for these parameters in order to control the data the result set returns. The final parameter is a String array that represents the "types of tables" on which you want information. This is not the data type of the table, but the category. The table types are database−dependent and the getTableTypes() method will provide a result set containing the types available. Examples of different table types are TABLE, VIEW, and SYSTEM. The following code snippet illustrates the getTables() method: //Assume a valid Connection object conn DatabaseMetaData dmd = conn.getMetaData(); //Define parameters. String catalog = null; String schema = "TODDT"; String tableName = "E%"; String [] types = {"TABLE"}; //Create a ResultSet object to hold the table information ResultSet rs = dmd.getTables(catalog, schema, tableName, types); Before calling the getTables() method, I first initialize all the parameters. I set the catalog parameter to null, which tells the method to ignore this parameter. In fact, you may inform the method to ignore any parameter by setting it to null. The null is equivalent to the asterisk (*) token in an SQL SELECT statement. The next parameter is the schema name. In this example, I only want to retrieve the tables from my schema, TODDT. The third parameter is a string pattern that represents the tables to include in the result set. In the previous snippet I want to retrieve all tables that begin with the letter E. Therefore I include the % character to represent any characters after E. The fourth parameter uses a String array to define which category of tables to include in the result set. The result set that the getTable() method returns has the following five columns: catalogname, schema name, table name, table type, and remarks. In my example, all the columns are Strings, so I can use the ResultSet.getString() method to retrieve the information. You also use the getColumn() method in a similar manner. The following code demonstrates its use: //Assume a valid Connection object conn DatabaseMetaData dmd = conn.getMetaData(); //Create a ResultSet object that holds the database table //information. String catalog = null; String schema = "TODDT"; String tableName = "E%"; String columnName = null; ResultSet rsCols=dmd.getColumns(null, schema, tableName, null); Of the four parameters, the last three accept string patterns. The first parameter is the same as the getTables() Chapter 8: Mining Database Metadata with JDBC 143 method as it specifies the catalog you wish to work with. The next parameter identifies the schema, which I specify as myself because I only want columns for tables in my schema. With the next parameter I use a string pattern to select only the tables in my schema that start with the letter E. The last parameter enables me to specify a column name. I can also use a string pattern here to limit the number of columns returned, but in this case I want all the columns and so I use a null value. The getColumns() method returns a result set that has 18 columns, and that unlike the result set returned by the getTables() method has mixed data types. Nonetheless, examples of the information the result set provides are the column name, data type, numeric precision if applicable, and whether the column can store null values. You should refer to the Javadocs for more information on the result set returned by the getColumns() method. Data type metadata You can determine what data types your target database supports by using the getTypeInfo() method. The result set returned by this method is complex. Like the getColumnMethod() it has 18 columns and provides information such as the data type name, case sensitivity, JDBC data type, and whether the column can contain null values. You may find this method useful if you want to write a utility program to determine the data types in a database. The following code snippet demonstrates a routine you can use to list all data types in a database. It provides the database’s name for the data type and the corresponding short value that represents the JDBC data type. //Assume a valid Connection object conn DatabaseMetaData dmd = conn.getMetaData(); //Create result set ResultSet rs = dmd.getTypeInfo(); //Loop through result set while(rs.next()){ System.out.println(rs.getString("TYPE_NAME") + " " + rs.getShort("DATA_TYPE")); } In addition, you can use the getUDT() method to obtain a result set containing the information about the UDTs on your database server. Primary− and foreign−key metadata A DatabaseMetaData object can also provide you with information on the referential integrity constraints for a database or group of tables. The getPrimaryKeys() and getImportedKeys() methods provide the primary− and foreign−key information. You may find these methods useful if you are writing an application to document your database. Stored procedure metadata If you need to obtain information about the stored procedures in a database, use the getProcedures() and getProcedureColumns() methods of the DatabaseMetaData object. DatabaseMetaData example As with most JDBC topics an example is worth a thousand words. Listing 8−2 provides an example of several of the DatabaseMetaData methods described in the previous section. The program starts by listing the name and version of the database to which I am connected. Next it lists all the tables in my schema, TODDT, along with the column data types, and primary and foreign keys. The next items it lists are the supported data types in the database. Notice that the getTypeInfo() method creates a result set that provides both the data type name as defined on the server and the JDBC data type. You can look up the numeric value returned to get a Chapter 8: Mining Database Metadata with JDBC 144 meaningful type name. Lastly, the program calls getSQLKeywords(), getNumericFunctions(), getStringFunctions(), and getTimeDateFunctions() methods to retrieve a list of the database keywords and helper functions. Listing 8−2: DBMetaData.java package Chapter8; //Specific imports import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.DatabaseMetaData; public class DBMetaData { public static void main(String[] args) { //Create Connection, Statement, and ResultSet objects Connection conn = null; Statement stmt = null; ResultSet rs = null; //Begin standard error handling try{ //Load a driver String driver = "oracle.jdbc.driver.OracleDriver"; Class.forName(driver).newInstance(); //Obtain a Connection object System.out.println("Connecting to database "); System.out.println(); String jdbcUrl = "jdbc:oracle:thin:@myserver:1521:ORCL"; String user = "TODDT"; String pwd = "mypwd"; conn = DriverManager.getConnection(jdbcUrl,user,pwd); //Initialize a DatabaseMetaData object DatabaseMetaData dmd = conn.getMetaData(); //Retrieve database name and version String dbname = dmd.getDatabaseProductName(); dbname = dbname + " " + dmd.getDatabaseProductVersion(); System.out.println("Database information:"); System.out.println(dbname); System.out.println(); //Retrieve a result set with table information String [] types = {"TABLE"}; rs = dmd.getTables(null,user,null,types); while(rs.next()){ String tableName = rs.getString(3); System.out.println("Table Name: " + tableName); System.out.println(" Column, Data Type"); ResultSet rsCols=dmd.getColumns(null,user,tableName,null); Chapter 8: Mining Database Metadata with JDBC 145 while(rsCols.next()){ System.out.println(" " + rsCols.getString("COLUMN_NAME") + ", " + rsCols.getString("TYPE_NAME")); }//end while rsCols System.out.println(); //Get primary keys for tables ResultSet rsPkey=dmd.getPrimaryKeys(null,user,tableName); if(rsPkey.next()){ System.out.println(" PK Name, Column Name"); do{ System.out.println(" " + rsPkey.getString("PK_NAME") + ", " + rsPkey.getString("COLUMN_NAME")); }while(rsPkey.next()); System.out.println(); }//end primary key //Get foreign keys for tables ResultSet rsFkey=dmd.getImportedKeys(null,user,tableName); if(rsFkey.next()){ System.out.println(" FK Name, FK Table, Column Name"); do{ System.out.println(" " + rsFkey.getString("FK_NAME") + ", " + rsFkey.getString("PKTABLE_NAME") + ", " + rsFkey.getString("FKCOLUMN_NAME")); }while(rsFkey.next()); System.out.println(); }//end foreign key }//end while for table information //Get supported data types rs = dmd.getTypeInfo(); System.out.println("Supported data types:"); while(rs.next()){ System.out.println("Database Type Name: " + rs.getString("TYPE_NAME") + " JDBC Type: " + rs.getShort("DATA_TYPE")); }//end while Chapter 8: Mining Database Metadata with JDBC 146 System.out.println(); //Retrieve SQL Keywords, numeric functions, string, and //time and date functions. System.out.println("SQL Keywords:"); String sql = dmd.getSQLKeywords(); System.out.println(sql); System.out.println(); System.out.println("Numeric Functions:"); String numeric = dmd.getNumericFunctions(); System.out.println(numeric); System.out.println(); System.out.println("String Functions:"); String string = dmd.getStringFunctions(); System.out.println(string); System.out.println(); System.out.println("Time and Date Functions:"); String time = dmd.getTimeDateFunctions(); System.out.println(time); System.out.println(); //Standard error handling } catch(SQLException se) { //Handle errors for JDBC se.printStackTrace(); } catch(Exception e) { //Handle errors for Class.forName e.printStackTrace(); } finally { try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end DBMetaData.java The output from Listing 8−2 is as follows: Connecting to database Database information: Oracle Oracle8i Enterprise Edition Release 8.1.7.0.0 − Production With the Partitioning option JServer Release 8.1.7.0.0 − Production Table Name: EMPLOYEES Chapter 8: Mining Database Metadata with JDBC 147 Column, Data Type SSN, NUMBER NAME, VARCHAR2 SALARY, NUMBER HIREDATE, DATE LOC_ID, NUMBER PK Name, Column Name PK_EMP, SSN FK Name, FK Table, Column Name FK_LOC, LOCATION, LOC_ID Table Name: LOCATION Column, Data Type LOC_ID, NUMBER LOCATION, VARCHAR2 PK Name, Column Name PK_LOC, LOC_ID Supported data types: Database Type Name: NUMBER JDBC Type: −7 Database Type Name: NUMBER JDBC Type: −6 Database Type Name: NUMBER JDBC Type: −5 Database Type Name: LONG RAW JDBC Type: −4 Database Type Name: RAW JDBC Type: −3 Database Type Name: LONG JDBC Type: −1 Database Type Name: CHAR JDBC Type: 1 Database Type Name: NUMBER JDBC Type: 2 Database Type Name: NUMBER JDBC Type: 4 Database Type Name: NUMBER JDBC Type: 5 Database Type Name: FLOAT JDBC Type: 6 Database Type Name: REAL JDBC Type: 7 Database Type Name: VARCHAR2 JDBC Type: 12 Database Type Name: DATE JDBC Type: 93 Database Type Name: STRUCT JDBC Type: 2002 Database Type Name: ARRAY JDBC Type: 2003 Database Type Name: BLOB JDBC Type: 2004 Database Type Name: CLOB JDBC Type: 2005 Database Type Name: REF JDBC Type: 2006 SQL Keywords: ACCESS, ADD, ALTER, AUDIT, CLUSTER, COLUMN, COMMENT, COMPRESS, CONNECT, DATE, DROP, EXCLUSIVE, FILE, IDENTIFIED, IMMEDIATE, INCREMENT, INDEX, INITIAL, INTERSECT, LEVEL, LOCK, LONG, MAXEXTENTS, MINUS, MODE, NOAUDIT, NOCOMPRESS, NOWAIT, NUMBER, OFFLINE, ONLINE, PCTFREE, PRIOR, all_PL_SQL_reserved_ words Numeric Functions: ABS, CEIL, COS, COSH, EXP, FLOOR, LN, LOG, MOD, POWER, ROUND, SIGN, SIN, SINH, SQRT, TAN, TANH, TRUNC, AVG, COUNT, GLB, LUB, MAX, MIN, STDDEV, SUM, VARIANCE String Functions: CHR, INITCAP, LOWER, LPAD, LTRIM, NLS,_INITCAP, NLS,_LOWER, NLS,_UPPER, REPLACE, RPAD, RTRIM, SOUNDEX, SUBSTR, SUBSTRB, TRANSLATE, UPPER, ASCII, INSTR, INSTRB, LENGTH, LENGTHB, NLSSORT, CHARTOROWID, CONVERT, HEXTORAW, Chapter 8: Mining Database Metadata with JDBC 148 RAWTOHEX, ROWIDTOCHAR, TO_CHAR, TO_DATE, TO_LABEL, TO_MULTI_BYTE, TO_NUMBER, TO_SINGLE_BYTE Time and Date Functions: ADD_MONTHS, LAST_DAY, MONTHS_BETWEEN, NEW_TIME, NEXT_DAY, ROUND, SYSDATE, TRUNC Goodbye! Summary This chapter provided an overview of the two metadata interfaces, ResultSetMetaData and DatabaseMetaData. These interfaces enable you to interrogate result sets and databases. Examples of information the ResultSetMetaData interface provides are: The number of columns in a result set.• The data types of the columns in a result set.• Examples of information the DatabaseMetaData interface provides are: The supported data types in a database.• The SQL keywords.• The names of helper functions for mathematical, character, and date and time calculations.• The tables, indices, and stored procedures in a database.• Whether or not the database supports batch−updates.• In addition, this chapter provided two examples showing how to use the interfaces. The ResultSetMetaData interface example includes a generic method that prints the data contained in a result set. The DatabaseMetaData interface example provided the routines used to list the table structure for any schema, the supported data type in the database, and also provided a list of SQL keywords and helper methods. Chapter 8: Mining Database Metadata with JDBC 149 Part III: Using Java Data Access Design Patterns Chapter List Chapter 9: Understanding Design Patterns Chapter 10: Building the Singleton Pattern Chapter 11: Producing Objects with the Factory Method Pattern Chapter 12: Creating a Façade Pattern 150 Chapter 9: Understanding Design Patterns In This Chapter Understanding design patterns• Using Java with design patterns• Relating design patterns to object−oriented programming• Applying design patterns to JDBC programming• The previous chapters of this book focused specifically on JDBC programming. The chapters in this part deviate slightly to introduce the subject of design patterns. Design patterns are software architectures used mainly with Object Oriented Programming (OOP) techniques and languages. Building software solutions using design patterns can produce software that has a high level of code reuse and is easy to maintain. The patterns are time−tested and even implemented within the Java API. Although used long before, design patterns were formally described and cataloged in the book Design Patterns (Addison−Wesley, 1995) by Gamma, Helm, Johnson, and Vlissides. After its publication, the subject became popular in the developer community. Programmers formed user groups to study and develop design patterns. Today, a search for “design patterns” on the Internet will provide you more information on the subject than you can absorb. Design Patterns introduced 23 patterns used in OO software design. The authors drew from their own experience and the experiences of others when they cataloged the patterns. The concepts they present certainly help me design software. Thinking in terms of patterns encourages me to consider objects as components and to take advantage of OO techniques such as encapsulation, inheritance, and polymorphism. I begin this chapter by introducing the subject of design patterns, and follow this with a short overview of the core patterns. Next, I cover implementation issues you will be faced with when using design patterns with Java. Throughout the chapter, I’ll also point out circumstances in which you can apply design patterns to JDBC programming. However, I save the details for Chapters 10, 11, and 12. What Are Design Patterns? Java is an object−oriented language that enables you to rapidly develop applications. It provides a class library, known as the Java API, which gives you reusable components so you do not have to develop them yourself. This enables you to focus on programming, because a lot of the low−level implementation work is handled for you. JDBC is a perfect example of a Java class library as it hides the complexities associated with interacting with a database, and lets you focus on the task at hand. However, despite Java’s class libraries, designing effective and efficient object−oriented software is hard. It takes experience to familiarize yourself with the best way to assemble objects to perform a particular task. You want a design that takes advantage of object−oriented traits such as code reusability, extensibility, and maintainability. In some cases you may need to sacrifice one trait in favor of another; overall, however, a good object−oriented design will have these attributes. 151 [...]... can act independently Template Method Uses a parent class to define methods and lets the derived classes provide the implementation Analogous to abstract methods in Java Command Allows an object to encapsulate a command as an object and send it to the Command object The Command object is responsible for dispatching the command to the appropriate object for execution Strategy Encapsulates a group of... or knowledge 155 Chapter 9: Understanding Design Patterns Java and Design Patterns As an object−oriented programming language, Java supports the implementation of the 23 design patterns presented in the previous section In fact, the Java API uses many of the patterns I just defined For example, the Enumeration interface implements an Iterator pattern It defines methods for retrieving data from an object... Row Number=2, SSN: Row Number=3, SSN: Row Number=4, SSN: Row Number =5, SSN: Goodbye! contents: 111111111, 41987 654 1, 312 654 987, 123 456 789, 987 654 321, Name: Name: Name: Name: Name: Todd, Salary: $50 00.0 Larry, Salary: $ 150 0.0 Lori, Salary: $2000. 95 Jimmy, Salary: $3080.0 John, Salary: $4 351 .0 Notice from the output that the object references for the ConnectionMgr variables are identical The same holds... Class B, the subclass, extends Class A and has access to the public or protected methods and data in class A In this example, Class B can access attribute1 and method1() because they are public It does not have access to private members attribute2 and method2() You are not restricted to using the base class’s methods and attributes; you can also add additional methods and properties to give Class B extra... technique of keeping together data structures and the methods (procedures) that act on them 157 Chapter 9: Understanding Design Patterns Figure 9−2: FruitBasket inheritance diagram Listing 9−1 demonstrates the polymorphic behavior with the Fruit class hierarchy Notice that I create two Fruit objects, Orange and Apple, and assign the variables references to instances of Orange and Apple objects Although... and Statement objects from the client Behavioral patterns This category focuses on algorithms, object responsibilities, and object−to−object communications You can think of these patterns as communication models that control how messages, object behavior, and state data are communicated between objects 154 Chapter 9: Understanding Design Patterns Because of its vast focus, this category is understandably... the two subclasses are Apple and Orange That is, Apple and Orange are of type Fruit because they extend the Fruit class and thereby share the same interface The base class has two members, a private String name and a public method, printName() Each subclass overrides the printName() method to print the value assigned to the name field Java OOP Terminology When working with Java you will often hear many... — such as user, password, or database — and retrieve an object with those properties Design patterns focus on object interactions and relationships As a result, they rely heavily on OOP techniques and concepts In particular, the patterns use class inheritance and object composition extensively In the remaining sections of this chapter I provide an overview of inheritance and composition, as well as... of OOP, is likely the most confusing OO term and concept The word is derived from the Greek for “many types” or “many forms.” Personally, I think of polymorphism in terms of interchangeable objects, because you can assign any subclass to a variable of the base class type 156 Chapter 9: Understanding Design Patterns Inheritance and polymorphism go hand in hand Inheritance provides a family of objects... in Java and how to apply them to design patterns Inheritance Inheritance is a technique for creating new classes based on other classes With Java, inheritance is achieved when one class extends another The class inherited from is called the super class or base class The inheriting, or extending, class is called the subtype or subclass The subclass has access to the public and protected methods and . java. sql.Connection; import java. sql.ResultSet; import java. sql.Statement; import java. sql.DriverManager; import java. sql.SQLException; import java. sql.DatabaseMetaData; public class DBMetaData { public. DriverManager.getConnection(jdbcUrl,user,pwd); //Initialize a DatabaseMetaData object DatabaseMetaData dmd = conn.getMetaData(); //Retrieve database name and version String dbname = dmd.getDatabaseProductName(); dbname. the two metadata interfaces, ResultSetMetaData and DatabaseMetaData. These interfaces enable you to interrogate result sets and databases. Examples of information the ResultSetMetaData interface

Ngày đăng: 14/08/2014, 06:21

Từ khóa liên quan

Mục lục

  • Part II: Understanding JDBC Programming Basics

    • Chapter 8: Mining Database Metadata with JDBC

      • The DatabaseMetaData Interface

        • DatabaseMetaData example

        • Summary

        • Part III: Using Java Data Access Design Patterns

          • Chapter 9: Understanding Design Patterns

            • In This Chapter

            • What Are Design Patterns?

            • Categories of Design Patterns

              • Creational patterns

              • Structural patterns

              • Behavioral patterns

              • Java and Design Patterns

                • Inheritance

                • Composition

                • Design-pattern implementation guidelines

                • Summary

                • Chapter 10: Building the Singleton Pattern

                  • In This Chapter

                  • What Is a Singleton Pattern?

                  • Structure of the Singleton Pattern

                  • Using the Singleton Pattern

                    • Basic Singleton example

                    • Connection manager Singleton example

                    • Summary

                    • Chapter 11: Producing Objects with the Factory Method Pattern

                      • In This Chapter

                      • What Is the Factory Method Pattern?

                      • Introducing the Factory Method Structure

Tài liệu cùng người dùng

Tài liệu liên quan