Getting Column Characteristics : ResultSetMetaData « Database « Java Tutorial






import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Main {
  public static void main(String[] args) throws Exception {
    Connection conn = getConnection();

    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int,myDate DATE);");
    String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";

    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
    pstmt.setString(1, "1");
    java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
    pstmt.setDate(2, sqlDate);

    pstmt.executeUpdate();

    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    ResultSetMetaData rsmd = rs.getMetaData();

    int numCols = rsmd.getColumnCount();

    System.out.print("\t");
    for (int i = 1; i <= numCols; i++) {
      System.out.println(rsmd.getColumnLabel(i));
    }

    System.out.print("\nAuto Increment\t");
    for (int i = 1; i <= numCols; i++) {
      System.out.println(rsmd.isAutoIncrement(i));
    }
    for (int i = 1; i <= numCols; i++) {

      System.out.println(rsmd.isCaseSensitive(i));
    }
    System.out.print("\nSearchable\t");
    for (int i = 1; i <= numCols; i++) {

      System.out.println(rsmd.isSearchable(i));
    }
    System.out.print("\nCurrency\t");
    for (int i = 1; i <= numCols; i++) {
      System.out.println(rsmd.isCurrency(i));
    }
    System.out.print("\nAllows nulls\t");
    for (int i = 1; i <= numCols; i++) {

      System.out.println(rsmd.isNullable(i));
    }
    System.out.print("\nSigned\t");
    for (int i = 1; i <= numCols; i++) {

      System.out.println(rsmd.isSigned(i));
    }
    System.out.print("\nRead only\t");
    for (int i = 1; i <= numCols; i++) {

      System.out.println(rsmd.isReadOnly(i));
    }
    System.out.print("\nWritable\t");
    for (int i = 1; i <= numCols; i++) {

      System.out.print(rsmd.isWritable(i));
    }
    System.out.print("\nDefinitely Writable\t");
    for (int i = 1; i <= numCols; i++) {

      System.out.println(rsmd.isDefinitelyWritable(i));
    }

    conn.close();
  }

  private static Connection getConnection() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:mem:data/tutorial";

    return DriverManager.getConnection(url, "sa", "");
  }
}








20.7.ResultSetMetaData
20.7.1.Get the Column Names in a Result Set
20.7.2.Get column count from ResultSetMetaData
20.7.3.ResultSetMetaData Methods for Information about a Result Set's Columns
20.7.4.ResultSetMetaData Methods for Property Information about a Result Set's Columns
20.7.5.Getting Column Characteristics
20.7.6.If a table column value is auto-increment?