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

结果

上述代码示例将产生以下结果。结果可能会有所不同。如果您的 JDBC 驱动程序安装不正确,您将收到 ClassNotfound 异常。

JDBC Class found
There are 2 record in the table
java_jdbc.html