Lấy nội dung Table trong JDBC trong Java



Miêu tả vấn đề

Cách thu nhận nội dung của một table bởi sử dụng kết nối JDBC?

Giải pháp

Ví dụ sau sử dụng các phương thức getString,getInt và executeQuery để lấy và hiển thị nội dung của Table trong JDBC.

import java.sql.*;public class jdbcResultSet {
   public static void main(String[] args) {
      try {
         Class.forName("org.apache.derby.jdbc.ClientDriver");
      }
      catch(ClassNotFoundException e) {
         System.out.println("Class not found "+ e);
      }
      try {
         Connection con = DriverManager.getConnection
         ("jdbc:derby://localhost:1527/testDb","username",
         "password");
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery
         ("SELECT * FROM employee");
         System.out.println("id  name    job");
         while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String job = rs.getString("job");
            System.out.println(id+"   "+name+"    "+job);
         }
      }
      catch(SQLException e){
         System.out.println("SQL exception occured" + e);
      }
   }
}

Kết quả

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

id  name   job
1   alok   trainee
2   ravi   trainee

java_jdbc_trong_java.jsp