How to get the datatype of a column of a table using JDBC?

JDBCJava 8Object Oriented ProgrammingProgramming

You can get the datatype of a column of a table using the getColumnType() method of the ResultSetMetaData class.

//Retrieving the ResultSetMetaData object
ResultSetMetaData rsmd = rs.getMetaData();

//getting the column type
String column_name = rsmd.getColumnTypeName(2);

Assume we have a table named employee_data in the database with the description as shown below:

+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| id       | int(11)      | YES  |     | NULL    |       |
| Name     | varchar(255) | YES  |     | NULL    |       |
| Dob      | date         | YES  |     | NULL    |       |
| Location | varchar(255) | YES  |     | NULL    |       |
+----------+--------------+------+-----+---------+-------+

Following JDBC program establishes connection with the database, retrieves the ResultSetMetaData object of the employee_data table, and prints the datatype of the third column.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class TypeOfColumn {
   public static void main(String args[])throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a Statement object
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("select * from employee_data");
      //Retrieving the ResultSetMetaData object
      ResultSetMetaData rsmd = rs.getMetaData();
      //getting the column type
      String column_name = rsmd.getColumnTypeName(3);
      System.out.println("Data type of the column with the specified index is: "+column_name);
   }
}

Output

Connection established......
Data type of the column with the specified index is: DATE
raja
Published on 02-Apr-2019 15:44:27
Advertisements