Mega Code Archive

 
Categories / Java / Database SQL JDBC
 

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();     }   } }