如何处理使用 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