How to Extract Information from ResultSet? - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

How to Extract Information from ResultSet?

Share This


If you run a select query where the number of columns and their data types are unknown, you may extract the number of attributes, their data types, etc from the populated result-set.

This technique is very important to understand when you are writing code to generate a dynamic view for an application.

package com.t4b.jdbc.mysql.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; public class ResultSetExtraction { public static void main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } try { Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test"); PreparedStatement pStatement = connection.prepareStatement("select * from users"); ResultSet rs = pStatement.executeQuery(); ResultSetMetaData rSetMetaData = rs.getMetaData(); int colCount = rSetMetaData.getColumnCount(); System.out.println("Columns are: "); for (int c = 1; c <= colCount; c++) { System.out.print(" " + rSetMetaData.getColumnName(c)); System.out.print(" " + rSetMetaData.getColumnDisplaySize(c)); System.out.print(" " + rSetMetaData.getColumnTypeName(c)); System.out.println(); } while (rs.next()) { for (int c = 1; c <= colCount; c++) { if (rSetMetaData.getColumnTypeName(c).equalsIgnoreCase("VARCHAR")) { System.out.print(" " + rs.getString(c)); } else if (rSetMetaData.getColumnTypeName(c).equalsIgnoreCase("NUMBER")) { System.out.print(" " + rs.getInt(c)); } else { // write code for other data types } } } } catch (SQLException e) { e.printStackTrace(); } } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.