如何使用 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
广告
© . All rights reserved.