每当JDBC应用程序在执行SQL语句时遇到问题时,都会引发SQLException。
此类提供有关与数据库交互时发生的错误的信息。
以下是SQLException类的主要方法:
| 序号 | 方法与说明 |
|---|---|
| 1 | intgetErrorCode()此方法返回发生异常的异常代码。 |
| 2 | SQLException setNextException(SQLException ex) 使用此方法,可以通过向当前异常添加新的异常来创建异常链。 |
| 3 | StringgetSQLState()此方法返回当前异常的SQLState。 |
| 4 | Iterator <Throwable>iterator()此方法返回一个迭代器,以迭代SQLExceptions链。 |
| 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 {
//注册驱动程序
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//获得连接
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
System.out.println("Connected to Oracle database....");
//创建语句
Statement stmt = con.createStatement();
//执行语句
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) {
//获取SQL错误代码
System.out.println("Code of the exception: "+e.getErrorCode());
//获取SQL状态
System.out.println("State of the exception: "+e.getSQLState());
//获取消息
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