包含以下主题:
- SQLException概述
- 检索异常
- 检索警告
- 分类的SQLExceptions
- SQLExceptions的其他子类
SQLException概述
当JDBC在与数据源交互期间遇到错误时,它会抛出SQLException的实例而不是Exception。SQLException实例包含以下信息,可帮助确定错误原因。
- 对错误的描述。SQLException.getMessage()方法可以获取一个该错误信息描述的String。
- SQLState代码。SQLException.getSQLState()方法检索此代码。
- 错误代码。这是一个整数值,用于标识导致SQLException实例被抛出的错误。它的值和含义是特定实现的,也可能是底层数据源返回的实际错误代码。SQLException.getErrorCode()方法来检索错误。
- 原因。一个SQLException实例可能有一个因果关系,由一个或多个Throwable引起的对象SQLExcepiton实例抛出。要导航此原因链,请递归调用该方法SQLException.getCause()直到返回null值。
- 对任何链式异常的引用,如果发生多个错误,则通过此链引用异常。通过调用SQLException.getNextException()来检索这些抛出的异常。
检索异常
public static void printSQLException(SQLException ex) { for (Throwable e : ex) { if (e instanceof SQLException) { if (ignoreSQLException( ((SQLException)e). getSQLState()) == false) { e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException)e).getSQLState()); System.err.println("Error Code: " + ((SQLException)e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while(t != null) { System.out.println("Cause: " + t); t = t.getCause(); } } } } }
对异常进行处理
public static boolean ignoreSQLException(String sqlState) { if (sqlState == null) { System.out.println("The SQL state is not defined!"); return false; } // X0Y32: Jar file already exists in schema if (sqlState.equalsIgnoreCase("X0Y32")) return true; // 42Y55: Table already exists in schema if (sqlState.equalsIgnoreCase("42Y55")) return true; return false; }
检索警告
SQLWarning对象是处理数据库访问警告的SQLException的一个子类。警告不会像异常那样停止执行应用程序,只是提醒用户某些事情没有按计划发生。
public static void getWarningsFromResultSet(ResultSet rs) throws SQLException { JDBCTutorialUtilities.printWarnings(rs.getWarnings()); } public static void getWarningsFromStatement(Statement stmt) throws SQLException { JDBCTutorialUtilities.printWarnings(stmt.getWarnings()); } public static void printWarnings(SQLWarning warning) throws SQLException { if (warning != null) { System.out.println("\n---Warning---\n"); while (warning != null) { System.out.println("Message: " + warning.getMessage()); System.out.println("SQLState: " + warning.getSQLState()); System.out.print("Vendor error code: "); System.out.println(warning.getErrorCode()); System.out.println(""); warning = warning.getNextWarning(); } }
posted on
浙公网安备 33010602011771号