Find column name using servlet

Find column name using servlet

Posted in : Java Posted on : July 8, 2011 at 6:26 PM Comments : [ 0 ]

In this section we will discuss how can we find out the column name of a table from the database.

Find column name using servlet

In this section we will discuss how can we find out the column name of a table from the database.

To solve this problem I made a class named GetColumnName which extends the HttpServlet class. Further inside the doGet() method I uses the getWriter() method of the HttpServletResponse which helps in to write on browser. As per the  solution of the given problem we are required there should be a connection between database and java program. So in the example I create a connection to the database. After creating a connection I used the SELECT Query and passed it into as a parameter of prepareStatement() method of Connection interface which returns a PreparedStatement object and the executeQuery() method executes the SQL query of this object and returns the ResultSet object. To find the column name we will have to first retrieves the information of the column. To do this I used the getMetaData() method of ResultSet which retrieves the number of column and its properties and returns it to the ResultSetMetaData object. Now we can find the number of columns and name of the columns using the ResultSetMetaData methods getColumnCount() and getColumnName(). getColumnCount() method returns the number of Columns available in table and getColumnName() method returns the Column names of the specified table.

Exmaple :

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class GetColumnName extends HttpServlet
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
PrintWriter pw = res.getWriter();
Connection con;
PreparedStatement ps;
ResultSet rs;
ResultSetMetaData rsmd;
con= DriverManager.getConnection("jdbc:odbc:formRecord");
ps = con.prepareStatement("select * from dataformat");
rs= ps.executeQuery();
rsmd = rs.getMetaData();
int clNo = rsmd.getColumnCount();
pw.println("Table has <b>"+clNo+"</b> columns<br>");
pw.println("Name of columns are ");
for(int i=1; i<= clNo; i++)
String clNm = rsmd.getColumnName(i);
catch(Exception e)


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Output :

At first I created a table which is as follows :

When you will execute the above java program you will find the following output :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics