Jdbc exception error code

Handling SQLExceptions

This page covers the following topics:

Overview of SQLException

When JDBC encounters an error during an interaction with a data source, it throws an instance of SQLException as opposed to Exception . (A data source in this context represents the database to which a Connection object is connected.) The SQLException instance contains the following information that can help you determine the cause of the error:

A description of the error. Retrieve the String object that contains this description by calling the method SQLException.getMessage .

A SQLState code. These codes and their respective meanings have been standardized by ISO/ANSI and Open Group (X/Open), although some codes have been reserved for database vendors to define for themselves. This String object consists of five alphanumeric characters. Retrieve this code by calling the method SQLException.getSQLState .

An error code. This is an integer value identifying the error that caused the SQLException instance to be thrown. Its value and meaning are implementation-specific and might be the actual error code returned by the underlying data source. Retrieve the error by calling the method SQLException.getErrorCode .

A cause. A SQLException instance might have a causal relationship, which consists of one or more Throwable objects that caused the SQLException instance to be thrown. To navigate this chain of causes, recursively call the method SQLException.getCause until a null value is returned.

A reference to any chained exceptions. If more than one error occurs, the exceptions are referenced through this chain. Retrieve these exceptions by calling the method SQLException.getNextException on the exception that was thrown.

Retrieving Exceptions

The following method, JDBCTutorialUtilities.printSQLException , outputs the SQLState, error code, error description, and cause (if there is one) contained in the SQLException as well as any other exception chained to it:

For example, if you call the method CoffeesTable.dropTable with Java DB as your DBMS, the table COFFEES does not exist, and you remove the call to JDBCTutorialUtilities.ignoreSQLException , the output will be similar to the following:

Instead of printing SQLException information, you could instead first retrieve the SQLState then process the SQLException accordingly. For example, the method JDBCTutorialUtilities.ignoreSQLException returns true if the SQLState is equal to code 42Y55 (and you are using Java DB as your DBMS), which causes JDBCTutorialUtilities.printSQLException to ignore the SQLException :

Retrieving Warnings

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. For example, a warning might let you know that a privilege you attempted to revoke was not revoked. Or a warning might tell you that an error occurred during a requested disconnection.

Читайте также:  Как зайти на микротик по маку

A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object. If getWarnings returns a warning, you can call the SQLWarning method getNextWarning on it to get any additional warnings. Executing a statement automatically clears the warnings from a previous statement, so they do not build up. This means, however, that if you want to retrieve warnings reported on a statement, you must do so before you execute another statement.

The following methods from JDBCTutorialUtilities.java illustrate how to get complete information about any warnings reported on Statement or ResultSet objects:

The most common warning is a DataTruncation warning, a subclass of SQLWarning . All DataTruncation objects have a SQLState of 01004 , indicating that there was a problem with reading or writing data. DataTruncation methods let you find out in which column or parameter data was truncated, whether the truncation was on a read or write operation, how many bytes should have been transferred, and how many bytes were actually transferred.

Categorized SQLExceptions

Your JDBC driver might throw a subclass of SQLException that corresponds to a common SQLState or a common error state that is not associated with a specific SQLState class value. This enables you to write more portable error-handling code. These exceptions are subclasses of one of the following classes:

  • SQLNonTransientException
  • SQLTransientException
  • SQLRecoverableException

See the latest Javadoc of the java.sql package or the documentation of your JDBC driver for more information about these subclasses.

Other Subclasses of SQLException

The following subclasses of SQLException can also be thrown:

  • BatchUpdateException is thrown when an error occurs during a batch update operation. In addition to the information provided by SQLException , BatchUpdateException provides the update counts for all statements that were executed before the error occurred.
  • SQLClientInfoException is thrown when one or more client information properties could not be set on a Connection. In addition to the information provided by SQLException , SQLClientInfoException provides a list of client information properties that were not set.

Источник

JDBC — Exceptions Handling

Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

Get your Java dream job! Beginners interview preparation

85 Lectures 6 hours

Core Java bootcamp program with Hands on practice

99 Lectures 17 hours

Exception handling allows you to handle exceptional conditions such as program-defined errors in a controlled fashion.

When an exception condition occurs, an exception is thrown. The term thrown means that current program execution stops, and the control is redirected to the nearest applicable catch clause. If no applicable catch clause exists, then the program’s execution ends.

JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the most common exception you’ll deal with is java.sql.SQLException.

SQLException Methods

An SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause.

The passed SQLException object has the following methods available for retrieving additional information about the exception −

Читайте также:  Ошибка 211 установка radeon software не может быть продолжена
Method Description
getErrorCode( ) Gets the error number associated with the exception.
getMessage( ) Gets the JDBC driver’s error message for an error, handled by the driver or gets the Oracle error number and message for a database error.
getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is returned from this method. For a database error, the five-digit XOPEN SQLstate code is returned. This method can return null.
getNextException( ) Gets the next Exception object in the exception chain.
printStackTrace( ) Prints the current exception, or throwable, and it’s backtrace to a standard error stream.
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream you specify.
printStackTrace(PrintWriter w) Prints this throwable and it’s backtrace to the print writer you specify.

By utilizing the information available from the Exception object, you can catch an exception and continue your program appropriately. Here is the general form of a try block −

Example

Study the following example code to understand the usage of try. catch. finally blocks.

Now, let us compile the above example as follows −

When you run JDBCExample, it produces the following result if there is no problem, otherwise the corresponding error would be caught and error message would be displayed −

Try the above example by passing wrong database name or wrong username or password and check the result.

Источник

Facing Issues On IT

JDBC : Exception and Warning Handling

SQLException is Checked Exception it encounters an error when interacting with database , executing query on Databases etc. It throws instance of SQLException.

SQLException contains several kind information on a database access error or other errors which can help to determine the cause of error:

  • Description of Error : A string describing the error mesage. It can be retrieved by SQLException.getMessage().
  • SQLStateCode : These codes and their respective meanings have been standardized by ISO/ANSI and Open Group (XOPEN), although some codes have been reserved for database vendors to define for themselves. This String object consists of five alphanumeric characters. Retrieve this code by calling the method SQLException.getSQLState().
  • DatabaseMetaData: The DatabaseMetaData method getSQLStateType can be used to discover whether the driver returns the XOPEN type or the SQL:2003 type.
  • ErrorCode: This is an integer value identifying the error that caused the SQLException instance to be thrown. Its value and meaning are implementation-specific and might be the actual error code returned by the underlying data source. Retrieve the error by calling the method SQLException.getErrorCode().
  • Exception Chaining: If more than one error occurs, the exceptions are referenced through this chain. Retrieve these exceptions by calling the method SQLException.getNextException() on the exception that was thrown.
  • Cause: A SQLException instance might have a causal relationship, which consists of one or more Throwable objects that caused the SQLException instance to be thrown. To navigate this chain of causes, recursively call the method SQLException.getCause() until a null value is returned.

Constructors

  • SQLException() : Constructs a SQLException object.
  • SQLException(String reason) : Constructs a SQLException object with given reason.
  • SQLException(String reason, String SQLState) : Constructs a SQLException with given reason and SQLState.
  • SQLException(String reason, String SQLState, int vendorCode) : Constructs a SQLException with given reason ,SQLState and vendorCode.
  • SQLException(String reason, String SQLState, int vendorCode, Throwable cause) : Constructs a SQLException with given reason ,SQLState ,vendorCode and cause.
  • SQLException(String reason, Throwable cause) : Constructs a SQLException with given reason and cause.
  • SQLException( Throwable cause) : Constructs a SQLException with given cause.
Читайте также:  Error hy000 odbc ошибка

SQLException Sub-classes

Our JDBC driver might throw a subclass of SQLException that corresponds to a common SQLState or a common error state that is not associated with a specific SQLState class value. This enables you to write more portable error-handling code. These exceptions are subclasses of one of the following classes:

  • BatchUpdateException
  • RowSetWarning
  • SerialException
  • SQLClientInfoException
  • SQLNonTransientException
  • SQLRecoverableException
  • SQLTransientException
  • SQLWarning
  • SynchFactoryException
  • SynchProviderException

Lets focus on some most common happening SQLException:

BatchUpdateException

BatchUpdateException is thrown when an error occurs during a batch update operation. In addition to the information provided by SQLException, BatchUpdateException provides the update counts for all statements that were executed before the error occurred.

SQLClientInfoException

SQLClientInfoException is thrown when one or more client information properties could not be set on a Connection. In addition to the information provided by SQLException, SQLClientInfoException provides a list of client information properties that were not set.

SQLWarning

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions they simply alert the user that something did not happen as planned. For example, a warning might let you know that a privilege you attempted to revoke was not revoked. Or a warning might tell you that an error occurred during a requested disconnection.

A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object. If getWarnings returns a warning, you can call the SQLWarning method getNextWarning on it to get any additional warnings. Executing a statement automatically clears the warnings from a previous statement, so they do not build up. This means, however, that if you want to retrieve warnings reported on a statement, you must do so before you execute another statement.

Example of SQLWarning

The most common warning is a DataTruncation warning, a subclass of SQLWarning. All DataTruncation objects have a SQLState of 01004, indicating that there was a problem with reading or writing data. DataTruncation methods let you find out in which column or parameter data was truncated, whether the truncation was on a read or write operation, how many bytes should have been transferred, and how many bytes were actually transferred.

Complete Example for Handling SQLException and Warning

In below example i have created one JDBC utilities class which will help to handle SQLException, SQLWarning chained Exception related to Connection, Statement and ResultSet etc. Here you will also see like how we can skip particular warning and exceptions.

Utilities Class to Handle JDBC Exception and Warnings

below is one SQlException output detail for one example where String value retrive with getInt()

For more other JAVA/JDBC issues solution follow link JDBC Issues and Solutions.

Источник

Smartadm.ru
Adblock
detector