0

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

Shakti
  • 89
  • 2
  • 3
  • 10

2 Answers2

0

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

%>
Rishi Php
  • 1,428
  • 11
  • 20
0

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)
{
  1. get the parameters using

    request.getParameter

  2. Connect to DB, Select id from table , iterate and if Id exists return a boolean variable with value true else return it as false

  3. 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

Creating simple JSP app

Start from here

Hope it Helps !!

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56