如何使用 Java 中的 JDBC 連線資料庫



問題描述

如何使用 JDBC 連線資料庫?假設資料庫名稱為 testDb,其中有一個名為 employee 的表,該表中有 2 條記錄。

解決方案

以下示例使用 getConnection、createStatement 和 executeQuery 方法連線資料庫並執行查詢。

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://: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);
      }
   }
}

結果

上述程式碼示例將產生以下結果。結果可能有所不同。如果 JDBC 驅動程式安裝不當,則會出現 ClassNotfound 異常。

JDBC Class found
There are 2 record in the table
java_jdbc.htm
廣告