Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-get-example Java program to get data type of column field

Related Tutorials


 
 

Share on Google+Share on Google+

Java program to get data type of column field

Advertisement
In this example java program we have to get the data type of the database table fields.

Java program to get data type of column field

     

In this example java program we have to get the data type of the database table fields. For this purpose we have established database connection via JDBC and after connecting database we have get the data tables meta data for getting the data type of the table columns. Here we have used MySQL database for connection with the data table. Table structure for webpages table of database "any" is as follows:

 

 

 

 

ResultSet rs = st.executeQuery("SELECT * FROM webpages"); 
ResultSetMetaData rsmd = rs.getMetaData();

Above line of code gets ResultSetMetaData object which will be further used for getting related information. We can use the getColumnCount() methods for getting the column index and these index will be used for getting column type and with the getColumnTypeName(index) method of ResultSetMetaData class.

Here is the example code of GetColumnDataType.java as follows:

 GetColumnDataType.java

import java.sql.*;
public class GetColumnDataType {
  public static void main(String[] args) throws 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 data type is ="
   +rsmd.getColumnTypeName(i));
  }
  st.close();
  conn.close();
  }

Output:


C:\javaexamples>javac GetColumnDataType.java

C:\javaexamples>java GetColumnDataType
Connected
Name of [1] Column data type is =DOUBLE
Name of [2] Column data type is =VARCHAR
Name of [3] Column data type is =VARCHAR
Name of [4] Column data type is =BLOB

Download Source Code

 

Advertisement

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 24, 2008

Related Tutorials

Discuss: Java program to get data type of column field  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Rahul Padwal
October 4, 2012
JAVA

Java program to get data type of column field
DMCA.com