Java Reference
In-Depth Information
One of the most useful tools provided by JDBC is the capability to retrieve information about the data
returned in a
ResultSet
. This information is obtained using the JDBC
ResultSetMetaData
object
reviewed in the
next section
.
JDBC ResultSetMetaData
In addition, two methods have been added that use the
ResultSetMetaData
class to get information
about the table being edited. The two
MetaData
objects that follow are capable of returning the table
information required:
DatabaseMetaData
, which returns information at the database level
ResultSetMetaData
, which returns information at the
ResultSet
level
The reason for using the
ResultSetMetaData
object in this example is to restrict the column
information to just the columns being displayed and to defer discussion of the
DatabaseMetaData
object until
ResultSets
have been discussed, since it makes heavy use of
ResultSets
to return
information.
JDBC
ResultSetMetaData
provides access to different kinds of information about the data in a
table, including column names and data types. Some of the most useful
ResultSet
MetaData
methods are the following:
int getColumnCount()
String getColumnName(int column)
String getColumnTypeName(int column)
The following usage is very straightforward. To get the names of all columns in a table, for example, a
simple query is executed to return a
ResultSet
used to get the
ResultSetMetaData
. This is then
queried for the desired information.
String SQLCommand = "SELECT * FROM "+tableName+";";
try {
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQLCommand);
ResultSetMetaData md = rs.getMetaData();
String[] columnNames = new String[md.getColumnCount()];
for(int i=0;i<columnNames.length;i++){
columnNames[i] = md.getColumnLabel(i+1);
}
con.close();
}