如何處理使用 JDBC 應用程式時發生的異常?
只要 JDBC 應用程式在執行 SQL 語句時遇到問題,就會丟擲 SQLException。
此類提供了在與資料庫互動時發生的錯誤資訊。
以下是 SQLException 類的主要方法
| 序號 | 方法和說明 |
|---|---|
| 1 | int getErrorCode() 此方法返回發生異常的異常程式碼。 |
| 2 | SQLException setNextException(SQLException ex) 使用此方法,可以透過向當前異常新增新異常來建立異常鏈。 |
| 3 | String getSQLState() 此方法返回當前異常的 SQLState。 |
| 4 | Iterator<Throwable> iterator() 此方法返回一個迭代器,用於迭代 SQLException 鏈。 |
| 5 | void getNextException(SQLException ex) 此方法用於檢索此異常鏈中的下一個 SQLException。 |
示例
以下示例演示如何處理 SQL 異常。在此處,我們建立一個已存在的表,並打印發生的異常的程式碼、狀態和訊息。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class HandlingExceptions {
public static void main(String args[]) {
try {
//Registering the Driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//Getting the connection
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
System.out.println("Connected to Oracle database....");
//Creating the Statement
Statement stmt = con.createStatement();
//Executing the statement
String createTable = "CREATE TABLE Students( " + "Name VARCHAR(255), " + "Age INT NOT NULL, " + "Percentage INT)";
stmt.execute(createTable);
PreparedStatement pstmt = con.prepareStatement("INSERT INTO Student VALUES(?, ?, ?)");
pstmt.setString(1, "Raju");
pstmt.setInt(2, 19);
pstmt.setInt(3, 85);
pstmt.execute();
pstmt.setString(1, "Raja");
pstmt.setInt(2, 17);
pstmt.setInt(3, 67);
pstmt.execute();
ResultSet rs = stmt.executeQuery("Select *from Student");
while(rs.next()) {
System.out.print("Name: "+rs.getString("Name")+", ");
System.out.print("Age: "+rs.getInt("Age")+", ");
System.out.print("Percentage: "+rs.getString("Percentage"));
System.out.println();
}
} catch(SQLException e) {
//Getting the SQL error code
System.out.println("Code of the exception: "+e.getErrorCode());
//Getting the SQL state
System.out.println("State of the exception: "+e.getSQLState());
//Getting the message
System.out.println("Message: "+e.getMessage());
}
}
}輸出
Connected to Oracle database.... Code of the exception: 955 State of the exception: 42000 Message: ORA-00955: name is already used by an existing object
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP