Java Tutorial/Database/ResultSetMetaData

Материал из Java эксперт
Перейти к: навигация, поиск

Get column count from ResultSetMetaData

import java.sql.Connection;
import java.sql.DriverManager;
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 = getHSQLConnection();
    Statement st = conn.createStatement();
//    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,"nameValue")");
    st = conn.createStatement();
    ResultSet rs = st.executeQuery("SELECT * FROM survey");
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int numberOfColumns = rsMetaData.getColumnCount();
    System.out.println("resultSet MetaData column Count=" + numberOfColumns);
    st.close();
    conn.close();
  }
  private static Connection getHSQLConnection() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:data/tutorial";
    return DriverManager.getConnection(url, "sa", "");
  }
}





Get the Column Names in a Result Set

Given a ResultSet object, it is possible to get the column name, column type, table name (from which table this column came from), and position.



import java.sql.Connection;
import java.sql.DriverManager;
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(ResultSet.TYPE_SCROLL_INSENSITIVE,
        ResultSet.CONCUR_UPDATABLE);
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,"nameValue")");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st.executeUpdate("insert into survey (id,name ) values (3,"Tom")");
    st = conn.createStatement();
    ResultSet rs = st.executeQuery("SELECT * FROM survey");
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int numberOfColumns = rsMetaData.getColumnCount();
    // get the column names; column indexes start from 1
    for (int i = 1; i < numberOfColumns + 1; i++) {
      String columnName = rsMetaData.getColumnName(i);
      String tableName = rsMetaData.getTableName(i);
      System.out.println(columnName);
      System.out.println(tableName);
    }
    rs.close();
    st.close();
    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", "");
  }
}



ID
SURVEY
NAME
SURVEY


Getting Column Characteristics

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", "");
  }
}





If a table column value is auto-increment?

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Main {
  private static final String DRIVER = "com.mysql.jdbc.Driver";
  private static final String URL = "jdbc:mysql://localhost/testdb";
  private static final String USERNAME = "root";
  private static final String PASSWORD = "";
  public static void main(String[] args) throws Exception {
    Class.forName(DRIVER);
    Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("SELECT id, username FROM users");
    ResultSetMetaData metadata = resultSet.getMetaData();
    if (metadata.isAutoIncrement(1)) {
      System.out.println("Column ID is an auto-increment column");
    }
  }
}





ResultSetMetaData Methods for Information about a Result Set"s Columns

  1. int getColumnCount();
  2. int getColumnDisplaySize(int column);
  3. String getColumnLabel(int column);
  4. String getColumnName(int column);
  5. String getSchemaName(int column);
  6. int getPrecision(int column);
  7. int getScale(int column);
  8. String getTableName(int column);
  9. String getCatalogName(int column);
  10. int getColumnType(int column);
  11. String getColumnTypeName(int column);


ResultSetMetaData Methods for Property Information about a Result Set"s Columns

  1. boolean isAutoIncrement(int column);
  2. boolean isCaseSensitive(int column);
  3. boolean isSearchable(int column);
  4. boolean isCurrency(int column);
  5. int isNullable(int column);
  6. boolean isSigned(int column);
  7. boolean isReadOnly(int column);
  8. boolean isWritable(int column);
  9. boolean isDefinitelyWritable(int column);