Finding JDBC Metadata


You want to learn about a database or table.


Read the documentation provided by your vendor or database administrator. Or ask the software for a MetaData object.


There are two classes of metadata (data about data) that you can ask for: DatabaseMetaData and ResultSetMetaData . Each of these has methods that let you interrogate particular aspects. The former class is obtained from a get method in a Connection object; the latter from a get method in the given ResultSet. First, let’s look at RawSQLServlet , a “generic query” formatter. The user enters a query (which must begin with SELECT) into an HTML form, and a servlet (see Section 18.2) passes the query on to a database using JDBC. The response is interrogated and formatted into a neat little HTML table, using the column names from the ResultSetMetaData as the headings for the HTML table. Figure 20-2 shows the form for inputting the query and the resulting response from the servlet. The code for the RawSQLServlet class is in Example 20-11. The nice part about this program is that it responds to whatever columns are in the ResultSet, which need not be in the same order as they are in the database. Consider the two queries:

select name, address from userdb
select address, name from userdb

Any code that depends upon knowing the order in the database would look very strange indeed if the user query requested fields in a different order than they were stored in the database.

Figure 20-2. RawSQLServlet ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.