English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JDBC Exception Handling (SQLException)

Exception handling allows you to handle exception situations in a controlled manner, such as errors defined by the program.

When an exception occurs, an exception is triggered. The word 'throw' means that the current program stops executing and control is redirected to the nearest applicable catch clause. If there is no applicable catch clause, the execution of the program ends.

JDBC exception handling is very similar to Java exception handling, but for JDBC, the most common exception you need to handle is java.sql.SQLException.

SQLException method

In both drivers and databases, SQLException may occur. When such an exception occurs, an object of type SQLException is passed to the catch clause.

传递的SQLException对象具有以下可用于检索有关异常的其他信息的方法-

方法描述
getErrorCode( )

获取与异常关联的错误号。

getMessage( )

获取错误的 JDBC 驱动程序错误消息,由驱动程序处理,或者获取数据库错误的 Oracle 错误号和消息。

getSQLState( )

获取 XOPEN SQLstate 字符串。对于 JDBC 驱动程序错误,此方法不返回任何有用信息。对于数据库错误,将返回五位数的 xopensqlstate 代码。此方法可以返回 null。

getNextException( )

获取异常链中的下一个 Exception 对象。

printStackTrace( )

打印当前异常或可调用异常,并将其回溯到标准错误流。

printStackTrace(PrintStream s)

将此可丢弃对象及其回溯打印到指定的打印流。

printStackTrace(PrintWriter w)

打印这个一次性文件,并将其回溯到指定的打印编写器。

通过利用Exception对象提供的信息,您可以捕获异常并适当地继续执行程序。这是try块的一般形式-

try {
   // 您的异常代码介于这些大括号之间!!!
}
catch(Exception ex) {
   // 您的异常处理代码介于这两者之间 
   // 花括号,类似于exception子句 
   // 在PL / SQL块中。
}
finally {
   // 您必须始终执行的代码介于这两者之间 
   // 大括号。就像关闭数据库连接一样。
}

在线示例

研究以下示例代码以了解try....catch...finally块的用法。

// 步骤1.导入所需的软件包
import java.sql.*;
public class JDBCExample {
   // JDBC驱动程序名称和数据库URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";
   //Credenziali del database
   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   try{
      //Passo 2: Registrazione del driver JDBC
      Class.forName("com.mysql.jdbc.Driver");
      //Passo 3: Creazione della connessione
      System.out.println("Connessione al database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
      //Passo 4: Esecuzione della query
      System.out.println("Creazione dello statement...");
      Statement stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);
      //Passo 5: Estrazione dei dati dal risultato
      while(rs.next()){
         //Ricerca per nome di colonna
         int id = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
         //Visualizzazione dei valori
         System.out.print("ID: "+ id);
         System.out.print(", Età: "+ age);
         System.out.print(", Primo: "+ first);
         System.out.println(", Ultimo: "+ last);
      }
      //Passo 6: Pulizia dell'ambiente
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Elaborazione degli errori JDBC
      se.printStackTrace();
   catch(Exception e){
      //处理 Class.forName 的错误
      e.printStackTrace();
   }finally{
      //最终阻止用于关闭资源
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   //结束 try
   System.out.println("Ciao!");
//结束 main
//结束 JDBCExample

现在,让我们编译上面的示例,如下所示:

C:\>javac JDBCExample.java
C:\>

EsecuzioneJDBCExample,如果没有问题,它将产生以下结果,否则将捕获相应的错误并显示错误消息-

C:\>java JDBCExample
Connessione al database...
Creazione dello statement...
ID: 100, Età: 18, Primo: Zara, Cognome: Ali
ID: 101, Età: 25, Primo: Mahnaz, Cognome: Fatma
ID: 102, Età: 30, Primo: Zaid, Cognome: Khan
ID: 103, Età: 28, Primo: Sumit, Cognome: Mittal
C:\>

尝试传递错误的数据库名称或错误的用户名或密码来上面的示例,然后检查结果。