Home Java Java-get-example Java program to get column names of a table
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Java program to get column names of a table

Advertisement
In this example of getting the columns names we need to have connection with the database and then after we will get metadata of this table and find the columns name within the metadata.

Java program to get column names of a table

     

In this example of getting the columns names we need to have connection with the database and then after we will get metadata of this table and find the columns name within the metadata.

In our example program we have created a database connection with the data table within the MySQL database. The data table view is as follows:

 


 


To have metadata related manipulation we need to have an object of ResultSetMetaData and thereafter we can do the manipulation on the table related information.

ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();

Above lines of code creates an object of ResultSetMetaData and we can get the number of columns with the use of getColumnCount() methods. Now we can get the column names with the index value by the method getColumnName().Here is the example code of GetColumnName.java as follows:

GetColumnName.java

import java.sql.*;
public class GetColumnName {
  public static void main(String[] argsthrows Exception {
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/";
  String username = "root";
  String password = "root";
  String dbName= "any";
  Class.forName(driver);
  Connection conn = DriverManager.getConnection(url+dbName, username, password);
  System.out.println("Connected");
  Statement st = conn.createStatement();
  ResultSet rs = st.executeQuery("SELECT * FROM webpages");
  ResultSetMetaData rsmd = rs.getMetaData();
  int NumOfCol = rsmd.getColumnCount();
  for(int i=1;i<=NumOfCol;i++)
  {
  System.out.println("Name of ["+i+"] Column="+rsmd.getColumnName(i));
  }
  st.close();
  conn.close();
  }


Output:

C:\javaexamples>javac GetColumnName.java

C:\javaexamples>java GetColumnName
Connected
Name of [1] Column=id
Name of [2] Column=title
Name of [3] Column=url
Name of [4] Column=pageContent

 

Download Source Code

 

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


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: October 23, 2008

Related Tutorials

Ask Questions?    Discuss: Java program to get column names of a table  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com