My SQL and Java Developer’s Guide phần 6 doc

44 251 0
My SQL and Java Developer’s Guide phần 6 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 Using Metadata he information stored in a database table isn’t always everything you need when developing an application If you are writing a servlet that will be used to remotely administer the database, you might like to know about current database features, what databases are defined, and other information The JDBC specification and Connector/J provide access to several methods that allow an application to access information about the database as well as information about a ResultSet object In this chapter, we cover some of the more common and useful methods found in the DatabaseMetaData object For a complete listing, refer to Appendix C T Many of the methods allow arguments for determining which databases and tables the methods should return information from In these cases, you can use the full string name of the table, or you can use string patterns in which the % character is used to match or more characters and the underscore (_) is used to match one character Using Database Metadata Connector/J provides information about the database server behind a connection by using the DatabaseMetaData object This object is designed to provide information in five major areas: ■ ■ General Source Information ■ ■ Feature Support 197 198 Using Metadata ■ ■ Data Source Limits ■ ■ SQL Objects Available ■ ■ Transaction Support The code in Listing 9.1 provides a glimpse at some of the methods in each of these five areas The current JDBC specification and Connector/J implement hundreds of attributes and methods in the DatabaseMetaData object, and we can’t cover all of them here See Appendix B to learn about all the attributes and methods import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import javax.naming.*; //import javax.naming.spi.ObjectFactory; import javax.sql.DataSource; public class DatabaseInfo extends HttpServlet { public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { PrintWriter out = null; Connection connection = null; Statement statement; ResultSet rs; outResponse.setContentType("text/html"); out = outResponse.getWriter(); try { Context ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/AccountsDB"); connection = ds.getConnection(); DatabaseMetaData md = connection.getMetaData(); statement = connection.createStatement(); out.println(" Database Server Information"); out.println(""); Listing 9.1 A database metadata example (continues) Using Database Metadata out.println("General Source Information"); out.println("getURL() - " + md.getURL() + ""); out.println("getUserName() - " + md.getUserName() + ""); out.println("getDatabaseProductVersion - " + md.getDatabaseProductVersion() + ""); out.println("getDriverMajorVersion - " + md.getDriverMajorVersion() + ""); out.println("getDriverMinorVersion - " + md.getDriverMinorVersion() + ""); out.println("nullAreSortedHigh - " + md.nullsAreSortedHigh() + ""); out.println("Feature Support"); out.println("Data Source Limits"); out.println("getMaxRowSize - " + md.getMaxRowSize() + ""); out.println("getMaxStatementLength - " + md.getMaxStatementLength() + ""); out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + ""); out.println("getMaxConnections - " + md.getMaxConnections() + ""); out.println("getMaxCharLiteralLength - " + md.getMaxCharLiteralLength() + ""); out.println("SQL Object Available"); out.println("getTableTypes()
    "); rs = md.getTableTypes(); while (rs.next()) { out.println("
  • " + rs.getString(1)); } out.println("
"); out.println("getTables()
    "); rs = md.getTables("accounts", "", "%", new String[0]); while (rs.next()) { out.println("
  • " + rs.getString("TABLE_NAME")); } out.println("
"); out.println("Transaction Support"); out.println("getDefaultTransactionIsolation() - " + md.getDefaultTransactionIsolation() + ""); out.println("dataDefinitionIgnoredInTransactions() - " + md.dataDefinitionIgnoredInTransactions() + ""); Listing 9.1 A database metadata example (continues) 199 200 Using Metadata out.println("General Source Information"); out.println("getMaxTablesInSelect - " + md.getMaxTablesInSelect() + ""); out.println("getMaxColumnsInTable - " + md.getMaxColumnsInTable() + ""); out.println("getTimeDateFunctions - " + md.getTimeDateFunctions() + ""); out.println("supportsCoreSQLGrammar - " + md.supportsCoreSQLGrammar() + ""); out.println("getTypeInfo()
    "); rs = md.getTypeInfo(); while (rs.next()) { out.println("
  • " + rs.getString(1)); } out.println("
"); out.println(""); } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { doGet(inRequest, outResponse); } } Listing 9.1 A database metadata example (continued) When the code in Listing 9.1 executes, it displays five different areas of information, as we explained earlier Figures 9.1, 9.2, and 9.3 show the values displayed when the code executes against a test machine running MySQL 4.0 Getting the Object As the code in Listing 9.1 shows, the DatabaseMetaData object is obtained using code like the following: DatabaseMetaData md = connection.getMetaData(); Since the DatabaseMetaData object isn’t related to a statement or a query, you can request the object using the getMetaData() method once you’ve established a connection to a MySQL database Using Database Metadata Figure 9.1 Output from our database metadata example Figure 9.2 Additional output from the metadata example 201 202 Using Metadata Figure 9.3 The final two areas of output General Source Information The General Source Information methods associated with the DatabaseMetaData object are designed to give information about the MySQL database server in general and are not specific to one database or table The code in Listing 9.1 details just six of the many methods that provide information about the server Figure 9.1 shows the output generated from the following size methods: getURL()—Returns a string with the URL used to connect to the database server getUserName()—Returns the current user logged into the system on this connection getDatabaseProductVersion()—Returns the version number of the database server getDriverMajorVersion()—Returns the major version number of the JDBC driver—Connector/J in our case getDriverMinorVersion()—Returns the minor version number of the JDBC driver Using Database Metadata 203 nullsAreSortedHigh()—Returns a true/false value indicating whether nulls will be sorted before or after the data getTimeDateFunctions()—Returns all of the time/data functions available on the server getTypeInfo()—Returns a ResultSet object with all of the possible types supported by the database server The code to extract the information is rs = md.getTypeInfo(); while (rs.next()) { out.println("
  • " + rs.getString(1)); } Feature Support Some of the more useful parts of the DatabaseMetaData object are the methods associated with features supported on the server Figure 9.1 shows the output of the example methods: supportsAlterTableWithDropColumn()—Returns true/false if the server supports the ALTER TABLE command with a drop column supportsBatchUpdates()—Returns true/false if the driver and server support batch updates supportsTableCorrelationNames()—Returns true/false if the database server supports correlation names supportsPositionedDelete()—Returns true/false if the server supports positioned DELETE commands supportsFullOuterJoins()—Returns true/false if the server supports full nested outer joins supportsStoredProcedures()—Returns true/false if the server supports stored procedures supportsMixedCaseQuotedIdentifiers()—Returns true/false if identifiers can be mixed case when quoted supportsANSI92EntryLevelSQL()—Returns true/false if the server supports the entry-level SQL for ANSI 92 supportsCoreSQLGrammar()—Returns true/false if the server supports core ODBC SQL grammar What makes these methods useful is the fact that your application can execute different code based on the support provided by the MySQL and Connector/J You could write your application to support older versions of the database as well as the cutting-edge development version by keeping track of the features supported 204 Using Metadata Data Source Limits Figure 9.2 shows the output generated for the chosen methods under Data Source Limits These methods provide information on the total number of specified elements that will be returned or allowed The examples methods are getMaxRowSize()—Returns the maximum number of bytes allowed in a row getMaxStatementLength()—Returns the maximum length of a statement getMaxTablesInSelect()—Returns the maximum number of tables that can appear in a SELECT getMaxColumnsInTable()—Returns the maximum number of columns that can be defined in a table getMaxConnections()—Returns the maximum number of concurrent connections currently defined getMaxCharLiteralLength()—Returns the maximum number of characters allowed in a literal SQL Object Available The SQL Object Available methods are designed to give you information about table types and other information about the actual SQL objects in the database server Figure 9.2 shows an example of the output generated from these methods: getTableTypes()—Returns a ResultSet object with all of the table types available on the current server getTables(database, schema, table, types)—Returns all of the tables in a given database, having a specific schema, narrowed by table and type The schema parameter is ignored in Connector/J The code for the call looks like this: rs = md.getTables("accounts", "", "%", new String[0]); while (rs.next()) { out.println("
  • " + rs.getString("TABLE_NAME")); } The result returned by the getTables() method has the following columns available: TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TABLE_TYPE, REMARKS, TYPE_CAT, TYPE_SCHEM, TYPE_NAME, SEL_REFERENCING_COL_NAME, and REF_GENERATION Transaction Support Transaction support is new to MySQL and Connector/J, and the DatabaseMetaData object includes a few methods for determining transaction support, as shown in Figure 9.3 The two methods are: The ResultSet Metadata 205 getDefaultTransactionIsolation()—Returns the default transaction isolation Possible values are TRANSACTION_NONE, TRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ, and TRANSACTION_SERIALIZABLE dataDefinitionIgnoredInTransactions()—Returns true/false indicating whether data definition changes are ignored in a transaction The ResultSet Metadata The database metadata provides fairly consistent data concerning the server itself We can also use the ResultSet metadata Each time a query is made against the database, all of the data is stored in the appropriate data structures within the object Along with the data, we can also obtain information about the specific columns returned by the query The ResultSet object includes a method with the signature ResultSetMetaData getMetaData(); This method returns a ResultSetMetaData object containing a dozen or so methods that return all kinds of information about the columns returned in the result Let’s look at two different applications that show the majority of the available methods Getting Column Information In all of the applications to this point, we have assumed and hard-coded the columns in the query that we know exist in the database table If we have an application that allows the user to enter a query or if the structure of the database changes often, we might want to rely on the database itself to provide information about the columns The code in Listing 9.2 uses the ResultSetMetaData object’s methods to determine column information import import import import import import java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*; javax.naming.*; javax.sql.DataSource; public class SeeAccount extends HttpServlet { Listing 9.2 A ResultSet metadata example (continues) 206 Using Metadata public void doGet(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { PrintWriter out = null; Connection connection = null; Statement statement = null; ResultSet rs; try { outResponse.setContentType("text/html"); out = outResponse.getWriter(); Context ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup( "java:comp/env/jdbc/AccountsDB"); connection = ds.getConnection(); statement = connection.createStatement(); rs = statement.executeQuery("SELECT * FROM acc_acc"); ResultSetMetaData md = rs.getMetaData(); out.println(" Thumbnail Identification Record"); out.println(""); out.println("Account Information:"); while (rs.next()) { for (int i=1;i
  • Ngày đăng: 13/08/2014, 12:21

    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