In the JDBC programs there are majorly two types of errors exit one is SQLException and BatchException. The SQLException throws by the program if anything goes wrong with the database interaction like the connection not established or some query syntax is not correct. The BatchException only occurs if something goes wrong in the batch processing of the statements. Also we can retrieve the database warning in our program.


 


The program below illustrates how to deal with database warnings and SQLExceptions


 


package com.visualbuilder;


import java.sql.Connection;


import java.sql.DriverManager;


import java.sql.ResultSet;


import java.sql.SQLException;


import java.sql.Statement;


 


public class ExceptionAndWarningExample {


    public static void main(String[] args) {


        try {


                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");


            /** Getting Connection*/


                                Connection con = DriverManager.getConnection("jdbc:odbc:MyDsn","root","tiger");


                                System.out.println("Connection estalished");


            /** Creating Statement*/


                                Statement stmt = con.createStatement();


                                ResultSet rs=stmt.executeQuery("select from emp");


                stmt.close();


                con.close();


            }catch (ClassNotFoundException exp){


            exp.printStackTrace();


            }catch (SQLException exp) {


 


            while (exp != null) {


                                System.out.println("Message: " + exp.getMessage ());


                                System.out.println("SQLState: " + exp.getSQLState ());


                                System.out.println("ErrorCode: " + exp.getErrorCode ());


                                exp = exp.getNextException();


                                }


                        }


                }


        }


 


Output:-


Connection estalished


Message: [Oracle][ODBC][Ora]ORA-00936: missing expression


SQLState: S1000


ErrorCode: 936


 


The same way warnings can be handled as shown below :-


 


SQLWarning warn = stmt.getWarnings();


if (warn != null) {


System.out.println("\n---Warning---\n");


while (warn != null) {


System.out.println("Message: " + warn.getMessage());


System.out.println("SQLState: " + warn.getSQLState());


System.out.print("Vendor error code: ");


System.out.println(warn.getErrorCode());


System.out.println("");


warn = warn.getNextWarning();


}


}

                    

Copyright © 2010 VisualBuilder. All rights reserved