Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the data in ResultSet along with column names

I am retrieving columns names from a SQL database through Java. I know I can retrieve columns names from ResultSet too. So I have this sql query

 select column_name from information_schema.columns where table_name='suppliers' 

The problem is I don't know how can I get columns names from ResultSet and my code is

public void getAllColumnNames() throws Exception{  String sql = "SELECT column_name from information_schema.columns where table_name='suppliers'";  PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery(sql);  // extract values from rs   } 
like image 269
user1hjgjhgjhggjhg Avatar asked Jun 15 '14 12:06

user1hjgjhgjhggjhg


People also ask

How do I get a list of column names in ResultSet?

You can get the name of a particular column using the getColumnName() method of the ResultSetMetadata interface. This method accepts an integer value representing the index of a column and returns a String value representing the name of the specified column.

How do I get all columns from ResultSet?

You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.


2 Answers

ResultSet resultSet = statement.executeQuery("SELECT * from foo"); ResultSetMetaData rsmd = resultSet.getMetaData(); int columnsNumber = rsmd.getColumnCount(); while (resultSet.next()) {     for (int i = 1; i <= columnsNumber; i++) {         if (i > 1) System.out.print(",  ");         String columnValue = resultSet.getString(i);         System.out.print(columnValue + " " + rsmd.getColumnName(i));     }     System.out.println(""); } 

Reference : Printing the result of ResultSet

like image 95
Zeb Avatar answered Sep 25 '22 21:09

Zeb


1) Instead of PreparedStatement use Statement

2) After executing query in ResultSet, extract values with the help of rs.getString() as :

Statement st=cn.createStatement(); ResultSet rs=st.executeQuery(sql); while(rs.next()) {     rs.getString(1); //or rs.getString("column name"); } 
like image 28
Java Enthusiast Avatar answered Sep 25 '22 21:09

Java Enthusiast