Update/Edit entered data from database - servlet

Raman picture Raman · Jun 8, 2013 · Viewed 13.1k times · Source

I have prepared a form for inserting, viewing and deleting data and now I want to add option to edit that data but either I am following wrong way to do it or I dont know how to do that.

So can any one help me proceeding to edit the entered data ?? Should I give reference to old html page to edit or new page or .. ?? I know I haven't followed MVC structure but I wanted to do whole coding in single page so waiting for help.. Thank you.

These are my codes.

Datastore.html

<html>
    <head>
        <title>Data insertion form</title>
    </head>

    <body>

    <form method= "get" action="/datainsert/DataInsertTable">

    <h1><center>Enter the required information</center></h1>

    <table>
        <tr>
            <td>Name</td>
            <td> :- </td>
            <td><input type="text" name="name"></input></td>
        </tr>

        <tr>
            <td>Roll Number</td>
            <td> :- </td>
            <td><input type="text" name="roll"></input></td>
        </tr>

        <tr>
            <td>Class </td>
            <td> :- </td>
            <td><input type="text" name="clas"></input></td>
        </tr>

        <tr>
            <td>Mobile Number </td>
            <td> :- </td>
            <td><input type="text" name="mono"></input></td>
        </tr>

        <tr>
            <td></td>
            <td><input type="submit" value="Submit" width="16" onClick=alert("data stored.");></input></td>
        </tr>

    </table>


    </form>

    </body>
</html>

DataInsertTable.java

import java.io.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class DataInsertTable extends HttpServlet    {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException, ServletException    {

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        PrintWriter pwinsert = res.getWriter();


        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Statement st = null;


        out.println("<html>");
        out.println("<head>");
            out.println("<title>User Data</title>");

            out.println("<script language = JavaScript>");
            out.println("<function f1() {>");
            out.println("<{>");
            out.println("<function f1() {>");
            out.println("<alert('Select data');>");
            out.println("<}>");
            out.println("</script>");

            out.println("</head>");

        out.println("</head>");

        out.println("<body>");

        out.println("<center><u><h1>User Data</h1></u>");

        out.println("<form name='form' >");

            out.println("<table border="+2+ "> ");
                out.println("<tr>");
                    out.println("<td> Select </td>");
                    out.println("<td> Name </td>");
                    out.println("<td> Roll No. </td>");
                    out.println("<td> Class </td>");
                    out.println("<td> Mobile Number </td>");
                out.println("</tr>");


                String nm = req.getParameter("name");
                String roll = req.getParameter("roll");
                String clas = req.getParameter("clas");
                String mono = req.getParameter("mono");


                try {
                    Class.forName("oracle.jdbc.driver.OracleDriver");
                }
                catch(ClassNotFoundException ex)    {
                    System.out.println("driver not loaded");
                    System.exit(0);
                }


                String URL = "jdbc:oracle:thin:@192.168.106.87:1521:ora11g";
                String Username = "pratik";
                String Password = "pratik";






//Insert                
                try {
                    con = DriverManager.getConnection(URL,Username,Password);

                    if(req.getParameter("choise")==null)    {
                        ps = con.prepareStatement("INSERT INTO student (name, rollno, class, mobileno) VALUES (?, ?, ?, ? )");
                        ps.setString(1,nm); 
                        ps.setString(2,roll);
                        ps.setString(3,clas);
                        ps.setString(4,mono);


                        int i = ps.executeUpdate();
                        pwinsert.println(i);

                        if(i!=0)    {
                            pwinsert.println("data has been stored");
                        }
                        else    {
                            pwinsert.println("data could not be stored");
                        }
                    }
                }

                catch(Exception e)  {
                    pwinsert.println(e.getMessage());
                }


                String idr=null;

//Delete
//cond. nt neeeded (null)

                if(req.getParameter("choise")!=null)    {
                    nm = req.getParameter("choise");

                    idr = "DELETE from student WHERE name ='"+nm+"'";

                    try {
                        st=con.createStatement();
                        rs = st.executeQuery(idr);
                    }
                    catch (Exception e) {
                        e.getMessage();
                        System.out.println("Error " +e);
                    }

                    System.out.println("Data se deleted..."); 



                }

//Update

/*              String updt = "UPDATE student SET name ='"+nm +"',rollno='" + roll + "', class='"+ clas +"', mobileno='"+mono+"' WHERE name ='"+nm +"' ";

                PreparedStatement ps1 = null;  
                try {
                    ps1=con.prepareStatement(updt);
                } catch (SQLException e2) {
                    e2.printStackTrace();
                }  

                int i = 0;
                try {
                    i = ps1.executeUpdate();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }  
                if(i==1)  
                    out.println("success");  
                else  
                    out.println("failed"); 

*/

// edit             
                if(req.getParameter("choise")!=null)    {
                    nm = req.getParameter("choise");

                    idr = "UPDATE student SET name = ?, rollno = ?, class = ?, mobileno = ? WHERE name = ?";

                    try {
                        st=con.createStatement();
                        int rs1 = st.executeUpdate(idr);
                    }
                    catch (Exception e) {
                        e.getMessage();
                        System.out.println("Error " +e);
                    }

                    System.out.println("Data Edited..."); 

                }
                else    {

                    System.out.println("Select row..");
                }


/*              String upd = "UPDATE student SET name = ?, rollno = ?, class = ?, mobileno = ? WHERE name = ?"; 

                PreparedStatement prest = null;
                try {
                    prest = con.prepareStatement(upd);
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    prest.setString(1,"nm");
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    prest.setString(2,"roll");
                } catch (SQLException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
                try {
                    prest.setString(3,"clas");
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    prest.setString(4,"mono");
                } catch (SQLException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
                try {
                    prest.executeUpdate();
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                System.out.println("Updating Successfully!");

*/              

                idr = "SELECT * FROM student WHERE name IS NOT NULL";


                try {
                    st=con.createStatement();
                    rs = st.executeQuery(idr);
                }
                catch (Exception e) {
                    e.getMessage();
                    System.out.println("Error " +e);
                }

                try {
                    while (rs.next())   {
                        out.println("<tr>");
                        out.println("<td>" + "<input type=\"radio\" name=\"choise\" value=\"" + rs.getString(1) + "\" /> </br>" + "</td>");
                        out.println("<td>" + rs.getString(1) + "</td>" + "\t <td>" + rs.getInt(2) + "</td>" + "\t <td>" + rs.getString(3) + "</td>" + "\t <td>" + rs.getString(4));
                        out.println("</tr>");
                    }

                    out.println("<tr>");
                    out.println("<td> </td>");
{                   
                    out.println("<td>" + "<input type=\"submit\" value=\"Delete Data\" />" + "</td>");

                    if(req.getParameter("choise") != null)  {

                        out.println("submitted.");
                    }

                    else    {
                        out.println("<script>alert('Data stored into database')</script>");
                    }
            }


// To Edit 
                    out.println("<td>" + "<input type=\"button\" value=\"Edit \" onClick = f1() />" + "</td>");


                    out.println("<td> </td>");
                    out.println("<td> </td>");
                    out.println("</tr>");
                }

                catch (Exception e) {
                    e.getMessage();
                    System.out.println("Error" +e);
                }

                try {
                    rs.close();
                }
                catch (Exception e) {
                    e.getMessage();
                    System.out.println("Error" +e);
                }

                try {
                    st.close();
                }
                catch (Exception e) {
                    e.getMessage();
                    System.out.println("Error" +e);
                }

                out.println("</table>");
                out.println("</form>");
                out.println("</center>");
                out.println("</body>");
                out.println("</html>");
                out.close();
            }
    }

Answer

shreyansh jogi picture shreyansh jogi · Jun 10, 2013

firstly on the page HTML page create one hidden field to identify which operation you want to perform initially its value should be blank and based on click whether insert update or delete assign some unique values to all the available operations.and from your servlets get that field as req.getParameter("<HIDDEN FIELD NAME>")and based on that put your code in respective if and else if block so that only that code will run. hope this will help