Home Tutorial Java Jdbc Get rows count and get columns names

 
 

Get rows count and get columns names
Posted on: May 31, 2010 at 12:00 AM
Advertisement
In this program , we will count the number of data rows stored in a table & also get column names.

COUNT ROWS AND GET COLUMN NAMES OF A TABLE  

In this program , we count the number of data rows stored in a table. 

getcolname.java  

import java.sql.*;
class getcolname 
{
  public static void main(String[] args) 
  {
  Connection con=null;
  Statement st=null;
  ResultSet rs=null;

  try
  {
    Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection("jdbc:mysql://192.168.10.13:3306/ankdb","root","root");
    st = con.createStatement();
    rs = st.executeQuery("select* from Employee");
    int count = 0;
    while(rs.next()) {
      count++;
                }
      System.out.println("Number of Rows present in table : "+count);

      ResultSetMetaData metaData = rs.getMetaData();

            int rowCount = metaData.getColumnCount();

      System.out.println("Table Name : " + metaData.getTableName(1));
      System.out.println("Field  \t\tDataType");

      for (int i = 0; i < rowCount; i++) {
      System.out.print(metaData.getColumnName(i + 1) + "  \t");
      System.out.println(metaData.getColumnTypeName(i + 1));
           }
      } catch (Exception e) {
        System.out.println(e);
      }
    }
}

In this program , we count the number of data rows stored in a table. This  will be done by using "ResultSet" object. And we will also get the name of the columns ,stored in a database. This will be done by using "ResultSet" ,"ResultSetMetaData" object and "getColumnName". We will also fetch the column's data types using the function "getColumnTypeName".Using "ResultsetmetaData" Object ,we can find properties of any table , like how many column its has or what is column name etc. 

OUTPUT   

 

Advertisement

Related Tags for Get rows count and get columns names:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 31, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com