JDBC的異常


以下內容引用自http://wiki.jikexueyuan.com/project/jdbc/exceptions.html

異常處理可以允許處理一個異常情況,例如可控方式的程序定義錯誤。

當異常情況發生時,將拋出一個異常。拋出這個詞意味着當前執行的程序停止,控制器被重定向到最近的適用的catch子句。如果沒有適用的catch子句存在,那么程序執行被終止。

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

一、SQLException方法

SQLException異常在驅動程序和數據庫中都可能出現。當出現這個異常時,SQLException類型的對象將被傳遞到catch子句。

傳遞的SQLException對象具有以下的方法,以下的方法可用於檢索該異常的額外信息:

方法 描述
getErrorCode( ) 獲取與異常關聯的錯誤號。
getMessage( ) 獲取JDBC驅動程序的錯誤信息,該錯誤是由驅動程序處理的,或者在數據庫錯誤中獲取Oracl錯誤號和錯誤信息。
getSQLState( ) 獲取XOPEN SQLstate字符串。對於JDBC驅動程序錯誤,使用該方法不能返回有用的信息。對於數據庫錯誤,返回第五位的XOPEN SQLstate代碼。該方法可以返回null。
getNextException( ) 獲取異常鏈的下一個Exception對象。
printStackTrace( ) 打印當前異常或者拋出,其回溯到標准的流錯誤。
printStackTrace(PrintStream s) 打印該拋出,其回溯到指定的打印流。
printStackTrace(PrintWriter w) 打印該拋出,其回溯到指定的打印寫入。

通過利用可從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塊的使用。

//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/Test?serverTimezone=UTC";

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

    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

當運行JDBCExample時,如果沒有問題它將展示下面的結果,否則相應的錯誤將被捕獲並會顯示錯誤消息:

 

測試工程:https://github.com/easonjim/5_java_example/tree/master/jdbcbasics/test6


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM