Kết nối Database sử dụng JDBC trong Java



Miêu tả vấn đề

Cách kết nối với Database sử dụng JDBC? Giả sử rằng tên Database là testDb và nó có Table với tên là employee mà có 2 record.

Giải pháp

Ví dụ sau sử dụng các phương thức getConnection, createStatement và executeQuery để kết nối với một Database và thực thi các truy vấn trong Java.

import java.sql.*;public class jdbcConn {
   public static void main(String[] args) {
      try {
         Class.forName("org.apache.derby.jdbc.ClientDriver");
      }
      catch(ClassNotFoundException e) {
         System.out.println("Class not found "+ e);
      }
      System.out.println("JDBC Class found");
      int no_of_rows = 0;
      try {
         Connection con = DriverManager.getConnection
         ("jdbc:derby://localhost:1527/testDb","username",
         "password");  
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery
         ("SELECT * FROM employee");
         while (rs.next()) {
            no_of_rows++;
         }
         System.out.println("There are "+ no_of_rows 
         + " record in the table");
      }
      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. Bạn sẽ nhận ClassNotfound exception nếu JDBC driver của bạn không được cài đặt đúng.

JDBC Class found
There are 2 record in the table

java_jdbc_trong_java.jsp