Saturday, May 9, 2015

How to get the column name of table dynamically in jdbc.

While displaying the table data in jdbc we have to get ResultSet object using ResultSet we are displaying the table data by using rs.getInt(1) or rs.getString(“name”) like this.

But, If we don’t know the column name or number of column in table  we can use ResultSetMetaData for this. Using ResultSetMetaData we can  get the number of column, type of column, name of column and so on.



In below example I’m displaying the “testuser” table data with column name.

Step 1- Get the connection refer previous post (http://atozjavatutorials.blogspot.in/2015/03/how-to-connect-mysql-database-in-java.html)

Step 2- Create    PreparedStatement and get the usertest table data.

1
PreparedStatement ps1=con.prepareStatement("select * from usertest");

Step 3- Execute the query and get the ResultSet

1
ResultSet rs=ps1.executeQuery();

Step 4- Using this ResultSet object call rs.getMetaData(); method to get the ResultSetMetaData object

1
ResultSetMetaData rsm= rs.getMetaData();

The ResultSet object having table data along with MetaData information.

Step 5- We can get the number of column in table using

1
int columnCount = rsm.getColumnCount();

Step 6- We can get the columns name using


1
2
rsm.getColumnName(1)
rsm.getColumnName(2)

Note: rsm.getColumnName(columnIndex) method need column index and the column index is base on 1 index but not 0 based index.

First column should be 1.

Example:

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com. atozjavatutorials;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class DBMetaData {
    private static ResultSetMetaData ResultSetMetaData;
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8", "root", "root");
        PreparedStatement ps1=con.prepareStatement("select * from usertest");
        ResultSet rs=ps1.executeQuery();
        ResultSetMetaData rsm= rs.getMetaData();
        int columnCount = rsm.getColumnCount();
        for (int i = 0; i < columnCount; i++) {
            System.out.print(rsm.getColumnName(i+1)+"\t\t");
        }
        System.out.println("\n===========================================");
        while(rs.next()){
            System.out.println(rs.getString(rsm.getColumnName(1))+"\t"+rs.getString(rsm.getColumnName(2)));
        }
    }
}

Output:

userid              photpath                    
===========================================
Ram Singh       images/Ram Singh
Shyam Singh    images/Shyam Singh

No comments :

Post a Comment