Get Error Code, SQL State, Message : SQLException « Database SQL JDBC « Java






Get Error Code, SQL State, Message

  

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SqlException {

  public static void main(String[] args) {

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {
      String driver = "oracle.jdbc.driver.OracleDriver";
      Class.forName(driver).newInstance();
      System.out.println("Connecting to database...");
      String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
      conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd");

      stmt = conn.createStatement();

      try {
        rs = stmt.executeQuery("Select * from no_table_exisits");
      } catch (SQLException seRs) {
        String exMsg = "Message from MySQL Database";
        String exSqlState = "Exception";
        SQLException mySqlEx = new SQLException(exMsg, exSqlState);
        seRs.setNextException(mySqlEx);
        throw seRs;
      }
    } catch (SQLException se) {
      int count = 1;
      while (se != null) {
        System.out.println("SQLException " + count);
        System.out.println("Code: " + se.getErrorCode());
        System.out.println("SqlState: " + se.getSQLState());
        System.out.println("Error Message: " + se.getMessage());
        se = se.getNextException();
        count++;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

   
  








Related examples in the same category

1.Logging errors to a file
2.Handling a SQL Exception: how to retrieve the information in a SQLException.
3.Print the stack trace for a SQLException to STDERR.