JDBC Exception object
JDBC Exception object can handle exception occur at run time. This exception class is java.sql.SQLException, when exception come details of exception are stored in SQLException object and we can go through these details.
e.g suppose we can table name which is not exists
<%
try{
sqlSelectRecord ="SELECT * FROM staff_register1";
psSelectRecord=conn.prepareStatement(sqlSelectRecord);
rsSelectRecord=psSelectRecord.executeQuery();
}
catch(SQLException sx)
{
sx.printStackTrace();
}
%>
Error will give details as
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'jsp.staff_register1' doesn't exist.
Sometimes JDBC exception is useful, can use for to stop duplicate entry in table.
First, make that column as unique key, if unique key column get duplicate entry SQL throw an error of duplicate Entry. This error can get at SQLException and print on JSP page.
Suppose us having unique key on sStaffName attribute of SQL table.
<%
try
{
sqlInsertRecord="insert into staff_register (sStaffName) values(?)";
psInsertRecord=conn.prepareStatement(sqlInsertRecord);
psInsertRecord.setString(1,staffName);
psInsertRecord.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
response.sendRedirect("addRecord.jsp");
//// On error it will send back to input page
}
%>
Error will
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry 'vikas' for key 'sStaffName'
|