Handling Errors
Collapse the table of content
Expand the table of content

Handling Errors

 

DownloadDownload JDBC Driver

When using the Microsoft JDBC Driver for SQL Server, all database error conditions are returned to your Java application as exceptions using the SQLServerException class. The following methods of the SQLServerException class are inherited from java.sql.SQLException and java.lang.Throwable; and they can be used to return specific information about the SQL Server error that has occurred:

  • getSQLState returns the standard X/Open or SQL99 state code of the exception.

  • getErrorCode returns the specific database error number.

  • getMessage returns the full text of the exception. The error message text describes the problem, and frequently includes placeholders for information, such as object names, that are inserted in the error message when it is displayed.

  • getNextException returns the next SQLServerException object or null if there are no more exception objects to return.

In the following example, an open connection to the SQL ServerAdventureWorks sample database is passed in to the function and a malformed SQL statement is constructed that does not have a FROM clause. Then, the statement is run and an SQL exception is processed.

public static void executeSQLException(Connection con) {
   try {
      String SQL = "SELECT TOP 10 * Person.Contact";
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(SQL);

      while (rs.next()) {
         System.out.println(rs.getString(4) + " " + rs.getString(6));
      }
      stmt.close();
   }
   catch (SQLException se) {
      do {
         System.out.println("SQL STATE: " + se.getSQLState());
         System.out.println("ERROR CODE: " + se.getErrorCode());
         System.out.println("MESSAGE: " + se.getMessage());
         System.out.println();
         se = se.getNextException();
      } while (se != null);
   }
}

Diagnosing Problems with the JDBC Driver

Community Additions

ADD
Show:
© 2016 Microsoft