i want to search record from database in jsp using id. if id exists in database then display edit.jsp otherwise display any error message like record not found in db.
Thanks
Try this : Selecting data from DB using MYSQL:
<%
Connection conn = null;
PreparedStatement ps1 = null;
ResultSet rs1 = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/<DATABASE_NAME>?user=<USER NAME>&password=<PASSWORD>");
if(!conn.isClosed())
out.println("MySql Connection Success..");
ps1 = conn.prepareStatement("SELECT *, count(*) as totalRecords FROM TABLE_NAME WHERE id = 1");
rs1 = ps1.executeQuery();
while (rs1.next()) {
if(rs1.getInt("totalRecords") > 0) {
out.println("Record Found");
} else {
out.println("Record Not Found");
}
}
} catch (Exception e) {
out.println("Error:"+e);
} finally {
if (rs1!= null) rs1.close();
if (ps1!= null) ps1.close();
if (conn!= null) conn.close();
}
%>
I guess it would be better if you use a servlet too . else you can go with the JSP itself , but you need to use scriplets , which is considered as a bad practice refer here.
In your servlet, do something like this ,
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
get the parameters using
request.getParameter
Connect to DB, Select id from table , iterate and if Id exists return a boolean variable with value true else return it as false
Check the value of the boolean variable if true , redirect it to edit.jsp else display an error msg
Note: For redirecting either use sendRedirect
or RequestDispatcher
. Refer this links could be more useful
Hope it Helps !!