Developer's Daily | Java Education |
front page | java | perl | unix | DevDirectory |
Front
Page Java Education Pure Java Articles |
|
Question: | How do I determine the number of columns in a ResultSet? |
Answer: |
When you send a SELECT statement to a database using JDBC, you'll read the query results into a ResultSet object. We demonstrated how to do this in our article on Creating and Executing an SQL Query. In many database programs you'll need to go a bit further, and dynamically determine the number of columns that are in a ResultSet object. As an example, I've been working on a Contact Management servlet-based Intranet application. Because I can dynamically determine the number of columns returned from my queries, I can write one QueryServlet to handle all of my database query needs. This makes it very easy to create a simple report writer for my Intranet app! You can get information about your ResultSet object, including the number of columns of data in the ResultSet, by creating a ResultSetMetaData object, and using it's methods to extract the desired information from the ResultSet object. Here's how to determine the number of columns in a ResultSet object: //------------------------------------------------------// // Here's the code to determine the number of columns // // in the ResultSet. // //------------------------------------------------------// Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * from Customer"); ResultSetMetaData rsmd = rs.getMetaData(); int numCols = rsmd.getColumnCount(); In this example, the variable numCols contains the number of columns of data that are in the ResultSet. As a final note, once you know the number of columns that are in a ResultSet, you can use the next() method of the ResultSet object to cycle through the columns and the ResultSet data.
|
Copyright 1998-2009 Alvin Alexander, devdaily.com
All Rights Reserved.