Sử dụng column method trong JDBC trong Java



Miêu tả vấn đề

Cách sử dụng các column method khác nhau để tính số lượng column, lấy tên column, lấy kiểu của column trong một Table trong JDBC?

Giải pháp

Ví dụ sau sử dụng các phương thức getColumnCount, getColumnName, getColumnTypeName, getColumnDisplaySize để lấy số lượng column, tên của column hoặc kiểu của column trong Table trong JDBC.

import java.sql.*;public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");
      Statement stmt = con.createStatement();
      String query = "select * from emp order by name";
      ResultSet rs = stmt.executeQuery(query);
      ResultSetMetaData rsmd = rs.getMetaData();
      System.out.println("no of columns in the table= "+
      rsmd.getColumnCount());
      System.out.println("Name of the first column "+ 
      rsmd.getColumnName(1));
      System.out.println("Type of the second column "+
      rsmd.getColumnTypeName(2));
      System.out.println("No of characters in 3rd column "+ 
      rsmd.getColumnDisplaySize(2));
   }
}

Kết quả

Code trên sẽ cho kết quả sau. Kết quả có thể rất đa dạng.

no of columns in the table= 3
Name of the first columnID
Type of the second columnVARCHAR
No of characters in 3rd column20

java_jdbc_trong_java.jsp