JDBC異常

異常處理允許我們以受控的方式處理異常情況,而不是直接退出程序,例如程序定義的錯誤。

發生異常時可以拋出異常。術語「異常」表示當前的程序執行停止,並且被重定向到最近的適用的catch子句。如果沒有適用的catch子句存在,則程序的執行結束。

JDBC異常處理與Java異常處理非常相似,但對於JDBC,要處理的最常見異常是java.sql.SQLException

SQLException方法

驅動程序和數據庫中都會發生SQLException。 發生這種異常時,SQLException類型的對象將被傳遞給catch子句。

傳遞的SQLException對象具有以下可用於檢索有關異常信息的方法 -

方法

描述

getErrorCode( )

獲取與異常關聯的錯誤代碼。

getMessage( )

獲取驅動程序處理的錯誤的JDBC驅動程序的錯誤消息,或獲取數據庫錯誤的Oracle錯誤代碼和消息。

getSQLState( )

獲取XOPEN SQLstate字符串。 對於JDBC驅動程序錯誤,不會從此方法返回有用的信息。 對於數據庫錯誤,返回五位數的XOPEN SQLstate代碼。 此方法可以返回null

getNextException( )

獲取異常鏈中的下一個Exception對象。

printStackTrace( )

打印當前異常或可拋出的異常,並將其追溯到標準錯誤流。

printStackTrace(PrintStream s)

將此throwable及其回溯打印到指定的打印流。

printStackTrace(PrintWriter w)

打印這個throwable,它是回溯到指定的打印器(PrintWriter)。

通過利用Exception對象提供的信息,可以捕獲異常並適當地繼續執行程序。下面是一個try塊的一般形式 -

try {
   // Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
   // Your exception handling code goes between these 
   // curly braces, similar to the exception clause 
   // in a PL/SQL block.
}
finally {
   // Your must-always-be-executed code goes between these 
   // curly braces. Like closing database connection.
}

實例

學習研究以下示例代碼以瞭解try …. catch … finally塊的用法。將下面代碼保存到文件:TryCatchFinally.java 中,

//STEP 1. Import required packages

import java.sql.*;

public class TryCatchFinally {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";

   //  Database credentials
   static final String USER = "root";
   static final String PASS = "123456";

   public static void main(String[] args) {
   Connection conn = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      Statement stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample

現在編譯上面例子中代碼如下 -

F:\worksp\jdbc>javac -Djava.ext.dirs=F:\worksp\jdbc\libs TryCatchFinally.java

執行上面編譯後的代碼,得到以下結果 -

F:\worksp\jdbc>java -Djava.ext.dirs=F:\worksp\jdbc\libs TryCatchFinally
Connecting to database...
Thu Jun 01 02:59:01 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Creating statement...
ID: 100, Age: 28, First: Max, Last: Su
ID: 101, Age: 25, First: Wei, Last: Wang
ID: 102, Age: 35, First: Xueyou, Last: Zhang
ID: 103, Age: 30, First: Jack, Last: Ma
ID: 106, Age: 28, First: Curry, Last: Stephen
ID: 107, Age: 32, First: Kobe, Last: Bryant
Goodbye!

F:\worksp\jdbc>