Tài liệu Java Database Programming Bible- P7 doc

50 303 1
Tài liệu Java Database Programming Bible- P7 doc

Đ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

Chapter 10:Building a Client/Server Application -300- } } catch(SQLException e){ reportException(e); } return typeVector; } The method getTableTypes() returns a ResultSet containing a single String column per row, identifying the table type. Typically, these types are as follows: § TABLE § VIEW § SYSTEM TABLE Using this table-type information, you can get the actual table names using the getTables() method. An example is shown in Listing 10-5. Listing 10-5: Retrieving tables public Vector getTables(String[] types){ Vector tableVector = new Vector(); try{ Connection con = DriverManager.getConnection(url,userName,password); DatabaseMetaData dbmd = con.getMetaData(); ResultSet rs = dbmd.getTables(null,null,"%",types); ResultSetMetaData md = rs.getMetaData(); int nColumns = md.getColumnCount(); while(rs.next()){ tableVector.addElement(rs.getString("TABLE_NAME")); } } catch(SQLException e){ reportException(e); } return tableVector; } The code to get the table names is similar to that used to get the table types. The most significant difference is in the argument list for the getTables() method. Since these types of arguments are fairly common when using metadata methods, it is worth discussing them in some detail. The getTables() method takes these four arguments: getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types); Here are explanations of each argument: TEAMFLY Team-Fly ® Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 10:Building a Client/Server Application -301 - § Catalog — a pair of double quotes ("") retrieves tables without a catalog, and null retrieves all tables. § SchemaPattern — a pair of double quotes ("") retrieves tables without a schema, and null retrieves all tables. § TableNamePattern — This is a table-name pattern similar to the argument used with SQL "LIKE". The"%" matches any substring of 0 or more characters, and "_" matches any one character. § Types — an array of table types to include; null returns all types. The getTables() method returns a ResultSet containing descriptions of the tables available in a catalog. The result set contains the columns shown in Table 10-1. Table 10-1: Columns Returned by getTables() Column Column Name Type Contents 1. TABLE_CAT String table_catalog (may be null) 2. TABLE_SCHEM String table_schema (may be null) 3. TABLE_NAME String table_name 4. TABLE_TYPE String table_type: "TABLE", "VIEW", "SYSTEM TABLE", etc. 5. REMARKS String remarks explanatory comment on the table Note Some databases may not return information for all tables. The DatabaseMetaData object also provides a mechanism to retrieve detailed information about the columns in a table through the use of the getColumns() method. Like the getTables() method, the getColumns() method returns a ResultSet. The method's argument list is also similar in that it takes a number of String patterns: public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern); Here are explanations of each argument: § Catalog — A pair of double quoutes ("") retrieves tables without a catalog, and null retrieves all tables. § SchemaPattern — The double quotes ("") retrieve tables without a schema, and null retrieves all tables. § TableNamePattern — This is a table name pattern similar to the argument used with SQL "LIKE". The "%" matches any substring of 0 or more characters; "_" matches any one character. § columnNamePattern— This is a column name pattern similar to the argument used with SQL "LIKE". The "%" matches any substring of 0 or more characters; "_" matches any one character. Using the table information that the code in Listing 10-5 returns, you can get column information using the getColumns() method. An example is shown in Listing 10-6. Listing 10-6: Retrieving column data public Vector getColumns(String tableName){ Vector columns = new Vector(); Hashtable columnData; try{ Connection con = DriverManager.getConnection(url,userName,password); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 10:Building a Client/Server Application -302 - DatabaseMetaData dbmd = con.getMetaData(); String catalog = con.getCatalog(); ResultSet rs = dbmd.getColumns(catalog,"%",tableName,"%"); ResultSetMetaData md = rs.getMetaData(); int nColumns = md.getColumnCount(); String value; while(rs.next()){ columnData = new Hashtable(); for(int i=1;i<=nColumns;i++){ value = rs.getString(i); if(value==null)value="<NULL>"; columnData.put(md.getColumnLabel(i),value); } columns.addElement(columnData); } } catch(SQLException e){ reportException(e); } return columns; } The code examples of Listings 10-5, 10-5, and 10-6 are additions to the DatabaseUtilities class. Further examples of the use of DatabaseMetaData are given later in this chapter. Note Many of the DatabaseMetaData methods have been added or modified in JDBC 2.0 and JDBC 3.0, so if your driver is not JDBC 2.0 or JDBC 3.0 compliant, a SQLException may be thrown by some DatabaseMetaData methods. Displaying DatabaseMetaData in a JTree The class required to display the table and column data retrieved from the DatabaseMetaData object is an extension of JInternalFrame. This is used to display a JTree in a JScrollPane, as shown in Listing 10-7. Listing 10-7: Displaying DatabaseMetaData in a JTree package JavaDatabaseBible.part2; import java.awt.*; import java.util.Hashtable; import java.util.Vector; import javax.swing.*; import javax.swing.JTree; import javax.swing.border.*; import javax.swing.tree.*; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 10:Building a Client/Server Application -303 - class MetaDataFrame extends JInternalFrame{ protected JTree tree; protected JScrollPane JTreeScroller = new JScrollPane(); protected DatabaseUtilities dbUtils; protected String dbName; protected String[] tableTypes; protected JPanel JTreePanel = new JPanel(); public MetaDataFrame(String dbName, DatabaseUtilities dbUtils){ setLocation(0,0); setClosable(true); setMaximizable(true); setIconifiable(true); setResizable(true); getContentPane().setLayout(new BorderLayout()); this.dbName=dbName; this.dbUtils=dbUtils; setTitle(dbName); init(); setVisible(true); } // initialise the JInternalFrame private void init(){ JTreePanel.setLayout(new BorderLayout(0,0)); JTreePanel.setBackground(Color.white); JTreeScroller.setOpaque(true); JTreePanel.add(JTreeScroller,BorderLayout.CENTER); DefaultTreeModel treeModel = createTreeModel(dbName); tree = new JTree(treeModel); tree.setBorder(new EmptyBorder(5,5,5,5)); JTreeScroller.getViewport().add(tree); JTreePanel.setVisible(true); JTreeScroller.setVisible(true); tree.setRootVisible(true); tree.setVisible(true); getContentPane().add(JTreePanel,BorderLayout.CENTER); } // Create a TreeModel using DefaultMutableTreeNodes protected DefaultTreeModel createTreeModel(String dbName){ DefaultMutableTreeNode treeRoot = new DefaultMutableTreeNode(dbName); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 10:Building a Client/Server Application -304 - Vector tableTypes = dbUtils.getTableTypes(); for(int i=0;i<tableTypes.size();i++){ DefaultMutableTreeNode tableTypeNode = new DefaultMutableTreeNode((String)tableTypes.elementAt(i)); treeRoot.add(tableTypeNode); String[] type = new String[]{(String)tableTypes.elementAt(i)}; Vector tables = dbUtils.getTables(type); for(int j=0;j<tables.size();j++){ DefaultMutableTreeNode tableNode = new DefaultMutableTreeNode(tables.elementAt(j)); tableTypeNode.add(tableNode); Vector columns = dbUtils.getColumns((String)tables.elementAt(j)); for(int k=0;k<columns.size();k++){ Hashtable columnData = (Hashtable)columns.elementAt(k); DefaultMutableTreeNode columnNode = new DefaultMutableTreeNode(columnData.get("COLUMN_NAME")); columnNode.add(new DefaultMutableTreeNode("TYPE_NAME: "+columnData.get("TYPE_NAME"))); columnNode.add(new DefaultMutableTreeNode("COLUMN_SIZE: "+columnData.get("COLUMN_SIZE"))); columnNode.add(new DefaultMutableTreeNode("IS_NULLABLE: "+columnData.get("IS_NULLABLE"))); tableNode.add(columnNode); } } } return new DefaultTreeModel(treeRoot); } } Most of the work in Listing 10-7 is done in the createTreeModel() method. This method first calls the getTableTypes() method shown in Listing 10-4 to get a vector of table-type names. These are used to create DefaultMutableTreeNodes attached to the root node representing the selected database. For each table type, a vector of table names of that type is returned by the getTables() method shown in Listing 10-5. These are used to create DefaultMutableTreeNodes that are attached to the table-type nodes representing each of the tables. Finally, for each table, a vector of Hashtables of column descriptors is obtained by calling the getColumns() method shown in Listing 10-6. This information is used to create the column node and column-information child nodes shown in Figure 10-2. Only a small amount of the available column information is used in this display for reasons of clarity. Additional fields that the getColumns() method makes available include those listed in Table 10-2. Table 10-2: Column Information Provided by getColumns() Column Name Type Meaning TABLE_CAT String table catalog (may be null) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 10:Building a Client/Server Application -305- Table 10-2: Column Information Provided by getColumns() Column Name Type Meaning TABLE_SCHEM String table schema (may be null) TABLE_NAME String table name COLUMN_NAME String column name DATA_TYPE short SQL type from java.sql.Types TYPE_NAME String Data source dependent type name COLUMN_SIZE int column size. DECIMAL_DIGITS int the number of fractional digits NUM_PREC_RADIX int Radix (typically either 10 or 2) NULLABLE int § columnNoNulls - might not allow NULL values § columnNullable - definitely allows NULL values § columnNullableUnknown - nullability unknown REMARKS String comment describing column (may be null) COLUMN_DEF String default value (may be null) CHAR_OCTET_LENGTH int the maximum number of bytes in the column ORDINAL_POSITION int index of column in table (starting at 1) IS_NULLABLE String § "NO" means column definitely does not allow NULLs. § "YES" means the column might allow NULL values. § An empty string means nullability unknown. In addition to information about the structure of the database, you will frequently find it useful to know something about the capabilities of the RDBMS itself. The methods supported by the DatabaseMetaData object to provide this type of information are discussed in the next section. Retrieving Information about RDBMS Functionality In addition to describing the structure of the database, the DatabaseMetaData object provides methods to access to a great deal of general information about the RDBMS itself. Some of the information you can retrieve about the database-management system is illustrated in Figure 10-3. The example shown in Figure 10-3 shows that the SQLServerContacts database is running under SQL Server 7, using the Opta2000 pure Java driver from i-net Software. Also listed are some of the features that this database configuration supports. The elapsed time shown in the status bar is the time to access and display the tree view of the DatabaseMetaData, as shown in Figure 10-2. The difference between the elapsed time of just over two seconds using the Opta2000 driver and nearly seven seconds using the jdbc-odbc bridge illustrated in Figure 10-3 is significant. The code required to retrieve this information is shown in Listing 10-8. Listing 10-8: Retrieving information about the RDBMS package JavaDatabaseBible.part2; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 10:Building a Client/Server Application -306 - import java.awt.*; import java.util.Hashtable; import java.util.Vector; import javax.swing.*; import javax.swing.JTree; import javax.swing.border.*; import javax.swing.tree.*; public class InfoDialog extends JDialog{ protected DatabaseUtilities dbUtils = null; protected JPanel dbInfoPanel = new JPanel(); protected JPanel featuresPanel = new JPanel(); protected JPanel topPanel = new JPanel(new BorderLayout()); protected JPanel centerPanel = new JPanel(new BorderLayout()); protected JPanel bottomPanel = new JPanel(new BorderLayout()); public InfoDialog(DatabaseUtilities dbUtils){ this.dbUtils=dbUtils; setTitle("Database Info"); getContentPane().setLayout(new BorderLayout()); String[] dbInfo = dbUtils.databaseInfo(); dbInfoPanel.setLayout(new GridLayout(dbInfo.length,1,2,2)); for(int i=0;i<dbInfo.length;i++){ dbInfoPanel.add(new JLabel(dbInfo[i])); } dbInfoPanel.setBorder(new CompoundBorder( new BevelBorder(BevelBorder.LOWERED), new EmptyBorder(2,2,2,2))); topPanel.add(new JLabel(" Database and Driver:"),BorderLayout.NORTH); topPanel.add(dbInfoPanel,BorderLayout.CENTER); getContentPane().add(topPanel,BorderLayout.NORTH); String[] features = dbUtils.featuresSupported(); featuresPanel.setLayout(new GridLayout(features.length,1,2,2)); for(int i=0;i<features.length;i++){ featuresPanel.add(new JLabel(features[i])); } featuresPanel.setBorder(new CompoundBorder( new BevelBorder(BevelBorder.LOWERED), new EmptyBorder(2,2,2,2))); centerPanel.add(new JLabel(" Supported Features:"),BorderLayout.NORTH); Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 10:Building a Client/Server Application -307 - centerPanel.add(featuresPanel,BorderLayout.CENTER); getContentPane().add(centerPanel,BorderLayout.CENTER); } } Clearly, this example illustrates only a small percentage of the data available through the use of the DatabaseMetaData object. It is well worth referring to the Javadocs available on the Sun Web site at: http://java.sun.com/j2se/1.4/docs/api/java/sql/package-summary.html. Note A shorter link is http://java.sun.com/docs/. This takes you to he main Javadocs page, and you can navigate from there. In addition to DatabaseMetaData methods, JDBC provides a large number of useful methods for accessing information about the ResultSet returned by a query. The next section discusses these methods. Using ResultSetMetaData The ResultSetMetaData object is similar to the DatabaseMetaData object, with the exception that it returns information specific to the columns in a ResultSet. Information about the columns in a ResultSet is available by calling the getMetaData() method on the ResultSet. The ResultSetMetaData object returned gives the number, types, and properties of its ResultSet object's columns. Table 10-3 shows some of the more commonly used methods of the ResultSetMetaData object. Table 10-3: ResultSetMetaData Methods ResultSetMetaData method Description getColumnCount() Returns the number of columns in the ResultSet getColumnDisplaySize(int column) Returns the column's max width in chars getColumnLabel(int column) Returns the column title for use in displays getColumnName(int column) Returns the column name getColumnType(int column) Returns the column's SQL data-type index getColumnTypeName(int column) Returns the name of the column's SQL data type getPrecision(int column) Returns the number of decimal digits in the column getScale(int column) Returns the number of digits to the right of the decimal point getTableName(int column) Returns the table name isAutoIncrement(int column) Returns true if the column is autonumbered isCurrency(int column) Returns true if the column value is a currency value isNullable(int column) Returns true if the column value can be set to NULL Listing 10-9 illustrates the use of the ResultSetMetaData methods getColumnCount and getColumnLabel in an example where the column names and column count are unknown. Listing 10-9: Using ResultSetMetaData public void printResultSet(String query){ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 10:Building a Client/Server Application -308- try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection ("jdbc:odbc:Inventory"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); ResultSetMetaData md = rs.getMetaData(); int nColumns = md.getColumnCount(); for(int i=1;i<=nColumns;i++){ System.out.print(md.getColumnLabel(i)+((i==nColumns)?"\n":"\t")); } while (rs.next()) { for(int i=1;i<=nColumns;i++){ System.out.print(rs.getString(i)+((i==nColumns)?"\n":"\t")); } } } catch(Exception e){ e.printStackTrace(); } } This example will print the ResultSet returned by a query to a file called "rs.txt". The command line to run the example is: java printResultSet jdbc:odbc:Contacts "SELECT * FROM CONTACT_INFO" The output is tab delimited, so that it can easily be imported into MSWord. The example first retrieves the column count for the ResultSet, then loops through the columns to get the column labels, which are printed as the first line. It then loops through all the rows, retrieving the data in an inner loop. Table 10-4 shows the ResultSet output by the command line shown above. Table 10-4: Formatting a ResultSet using ResultSetMetaData FIRST_NAME MI LAST_NAME STREET CITY STATE ZIP Michael A Corleone 123 Pine New York NY 10006 Fredo X Corleone 17 Main New York NY 10007 Sonny A Corleone 123 Walnut Newark NJ 12346 Francis X Corleone 17 Main New York NY 10005 Vito G Corleone 23 Oak St Newark NJ 12345 Tom B Hagen 37 Chestnut Newark NJ 12345 Kay K Adams 109 Maple Newark NJ 12345 Francis F Coppola 123 Sunset Hollywood CA 23456 Mario S Puzo 124 Vine Hollywood CA 23456 Michael J Fox 109 Sepulveda LA CA 91234 James A Caan 113 Sunset Hollywood CA 92333 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Chapter 10:Building a Client/Server Application -309 - Summary This chapter combines the examples in Chapters 5-9 to create the basis of a useful database- management tool and test platform. In the process, you learn about: § Using DatabaseMetaData § Using ResultSetMetaData § Comparing the performance of different drivers In Part 2 as a whole, you learn how to use the JDBC Core API to create, maintain, and query a database. You also gain hands-on experience in creating a practical client/server application Part III explores the JDBC 2.0 Extension API in the context of a web application example. Web applications tend to be heavily database oriented, since they frequently involve a lot of form handling, and the need to upload and download large data items using streams and large data base objects. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... radio buttons, where the JavaBean property is set to the selected radiobutton value You can test the use of JSP and JavaBeans using the simple JavaBean of Listing 12-7 This is the JavaBean originally used with the JSP code of Listing 12-6 Listing 12-7: Simple JavaBean illustrating getter and setter methods package JavaDatabaseBible.ch12; public class ParameterTestBean extends java. lang.Object{ protected... Conversion Method boolean or Boolean java. lang.Boolean.valueOf(String) byte or Byte java. lang.Byte.valueOf(String) char or Character, java. lang.Character.valueOf(String) int or Integer java. lang.Integer.valueOf(String) double or Double java. lang.Double.valueOf(String) integer or Integer java. lang.Integer.valueOf(String) float or Float java. lang.Float.valueOf(String) long or Long java. lang.Long.valueOf(String)... and Java Server Pages Chapter 12: Using JDBC DataSources with Servlets and Java Server Pages In This Chapter Servlets and Java Server Pages (JSP) extend the power of Java technology to server-side applications They are Java technology's answer to CGI programming, for they enable the developer to build dynamic Web pages combining user input with information from corporate data sources Server-side Java. .. The ability to load and execute a JavaBean by name is the real key to using JavaBeans as pluggable components Since the JavaBean is linked into the JSP at runtime rather than at compile time, the JSP can be edited and updated separately from the business logic in the JavaBean To call a Java Bean from a JSP, simply write this: The ... -325- Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Chapter 12:Using JDBC DataSources with Servlets and Java Server Pages Listing 12-3: Login servlet import java. io.*; import java. sql.*; import javax.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class DataSourceLoginServlet extends HttpServlet{ private static String dbUserName = "sa"; private static... using JDBC There is also an even easier way — you can use Java Server Pages Java Server Pages provide a means of using Java code within an HTML page Simply write the static HTML parts of the page in the normal way, and embed the Java code inside special tags The Java is executed in the JSP engine, and the result is sent to the client as HTML Note Java Server Pages are not limited to generating HTML JSP... most useful features of Java Server Pages is that JSP directly supports the use of JavaBeans through the tag Java Beans, as you probably know, are Java classes that can be loaded by name and otherwise conform to a specific set of rules These rules include the following: § Being a public class: public class JavaBean § Having a public, no argument constructor: public JavaBean () § Using private... of the SQL the JavaBean executes Before implementing the MVC approach to handling the login form, it is worth reviewing the use of JavaBeans with JSP pages The next few paragraphs give a brief overview -330- Team-Fly® Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Chapter 12:Using JDBC DataSources with Servlets and Java Server Pages Using JavaBeans with Java Server Pages... information from the database and forwards the message The final chapter of Part III of this book illustrates the use of JDBC with the JavaMail API The combination of JDBC and JavaMail lets you send e-mails to members automatically It also allows you to receive e-mails and save them directly to a database Summary This chapter provides an overview of the design of a three-tier, database- driven Web site... DataSources with Servlets and JavaServer Pages Chapter 13: Using PreparedStatements and CallableStatements Chapter 14: Using Blobs and Clobs to Manage Images and Documents Chapter 15: Using JSPs, XSL, and Scrollable ResultSets to Display Data Chapter 16: Using the JavaMail API with JDBC Part Overview AM FL Y A significant part of Java' s success has been its application to server-side programming One of the . Displaying DatabaseMetaData in a JTree package JavaDatabaseBible.part2; import java. awt.*; import java. util.Hashtable; import java. util.Vector; import javax.swing.*;. -306 - import java. awt.*; import java. util.Hashtable; import java. util.Vector; import javax.swing.*; import javax.swing.JTree; import javax.swing.border.*;

Ngày đăng: 26/01/2014, 18:20

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan