Programmatically getting column information of a database table in Java

You can get meta information on a table by invoking getMetaData on a connection. With the method getColumns, you get back a number of rows containing information about each column of a particular table. Check the api to see what you can query.

Main.java:

import java.util.*;
import java.text.*;
import java.sql.*;
  
public class Main {
   public static void main(String []args) throws Exception {
      try {
         Class.forName("org.gjt.mm.mysql.Driver").newInstance();
         Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.0.1/esus", 
                                                       "joris",
                                                       "mypass");
 
         DatabaseMetaData dbMeta = conn.getMetaData();
         ResultSet rs = dbMeta.getColumns(null, "", "orders", "%");
 
         while (rs.next()) {
            String column_name      = rs.getString(4);
            String sql_type         = rs.getString(5);
            String type_name        = rs.getString(6);
            String column_size      = rs.getString(7);
            String ordinal_position = rs.getString(17);
            String is_nullable      = rs.getString(18);
 
            System.out.println("Column " + column_name);
            System.out.println("tSQL_TYPE          = " + sql_type);
            System.out.println("tTYPE_NAME         = " + type_name);
            System.out.println("tCOLUMN_SIZE       = " + column_size);
            System.out.println("tORDINAL_POSITION  = " + ordinal_position);
            System.out.println("tIS_NULLABLE       = " + is_nullable);
         } 
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}

outputs:

Column orderid
	SQL_TYPE          = 4
	TYPE_NAME         = int
	COLUMN_SIZE       = 10
	ORDINAL_POSITION  = 1
	IS_NULLABLE       = NO
Column custid
	SQL_TYPE          = 4
	TYPE_NAME         = int
	COLUMN_SIZE       = 10
	ORDINAL_POSITION  = 2
	IS_NULLABLE       = YES
Column timestamp
	SQL_TYPE          = 93
	TYPE_NAME         = datetime
	COLUMN_SIZE       = 19
	ORDINAL_POSITION  = 3
	IS_NULLABLE       = YES
Column status
	SQL_TYPE          = -6
	TYPE_NAME         = tinyint
	COLUMN_SIZE       = 4
	ORDINAL_POSITION  = 4
	IS_NULLABLE       = YES