Java Reference
In-Depth Information
You can use the getColumnCount() method to find the number of columns in the result and
the getColumnName(int) method to get the column names. For example, ListingĀ 32.7 dis-
plays all the column names and contents resulting from the SQL SELECT statement select
* from Enrollment . The output is shown in FigureĀ 32.26.
L ISTING 32.7
TestResultSetMetaData.java
1 import java.sql.*;
2
3 public class TestResultSetMetaData {
4 public static void main(String[] args)
5 throws SQLException, ClassNotFoundException {
6 // Load the JDBC driver
7 Class.forName( "com.mysql.jdbc.Driver" );
8 System.out.println( "Driver loaded" );
9
10 // Connect to a database
11 Connection connection = DriverManager.getConnection
12 ( "jdbc:mysql://localhost/javabook" , "scott" , "tiger" );
13 System.out.println( "Database connected" );
14
15 // Create a statement
16 Statement statement = connection.createStatement();
17
18 // Execute a statement
19 ResultSet resultSet = statement.executeQuery
20 ( "select * from Enrollment" );
21
22 ResultSetMetaData rsMetaData = resultSet.getMetaData();
23 for ( int i = 1 ; i <= rsMetaData.getColumnCount(); i++)
24 System.out.printf( "%-12s\t" , rsMetaData.getColumnName(i));
25 System.out.println();
26
27 // Iterate through the result and print the students' names
28 while (resultSet.next()) {
29 for ( int i = 1 ; i <= rsMetaData.getColumnCount(); i++)
30 System.out.printf( "%-12s\t" , resultSet.getObject(i));
31 System.out.println();
32 }
33
34 // Close the connection
35 connection.close();
36 }
37 }
load driver
connect database
create statement
create result set
result set metadata
column count
column name
F IGURE 32.26
The ResultSetMetaData interface enables you to obtain result set
information.
 
 
Search WWH ::




Custom Search