Monday, May 24, 2010

Getting Column Names from a database table in Java

Here we are providing you an example with code that retrieves all columns name in a specific database table. Sometimes, you need to know the number of columns and the names of the columns of the table, so you can retrieve it with the help of this example. See detail information given below:

Description of program:

Create a class ColumnName. The name of the class should be such that the other person can easily understand what this program is going to do. Strictly follow the naming conventions of java. Now declare a static method inside which creates the connection with MySQL database through the JDBC driver. After establishing the connection then you get all columns name and number of columns of specified table with the help of some APIs and methods.

Description of code:

This is an interface of java.sql package that can be used for getting information about types and properties of columns in a ResultSet object.

Above method retrieves number of columns (integer types data) in the ResultSet object.

getColumnName(int column):
This method returns columns name (string type data) from ResultSetMetaData object and takes integer type value.

Here is the code of program:

import java.sql.*;

public class ColumnName{
public static void main(String[] args) {
System.out.println("Getting Column Names Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
con = DriverManager.getConnection(url+db, user, pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM employee6");
ResultSetMetaData md = rs.getMetaData();
int col = md.getColumnCount();
System.out.println("Number of Column : "+ col);
System.out.println("Columns Name: ");
for (int i = 1; i <= col; i++){
String col_name = md.getColumnName(i);
catch (SQLException s){
System.out.println("SQL statement is not executed!");
catch (Exception e){
Output of program:


C:\vinod\jdbc\jdbc-mysql>java ColumnName
Getting Column Names Example!
Number of Column : 2
Columns Name:

No comments:

Post a Comment