-1

My aim is to insert data into database from servlet. Here what I have tried: 1) Created simple servlet in which I create dbconnect which connects and inserts data to mysql database.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class logic extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("name");
        dbconnect con = new dbconnect();
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet logic</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet logic at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

2) dbconnect class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;


public class dbconnect {
    Connection conn;
    Statement stm;

    public dbconnect(){
    try{
        conn = DriverManager.getConnection("jdbc:mysql://villaikalto.ge/villaika_type?user=villaika_type&password=pass");
        stm = conn.createStatement();
        System.out.println("success");
        String sql = "INSERT INTO users (mail, pass, gender, saxeli) VALUES (?, ?, ?, ?)";
        System.out.println("1");
        PreparedStatement statement = conn.prepareStatement(sql);
        System.out.println("2");
        statement.setString(1, "tsogiaidze");
        statement.setString(2, "nika");
        statement.setString(3, "nika");
        statement.setString(4, "kaci");
        System.out.println("3");
        int rowsInserted = statement.executeUpdate();
        System.out.println("4");
        if (rowsInserted > 0) {
        System.out.println("A new user was inserted successfully!");
        }
      }  
      catch (Exception ex){
          System.out.println("error");
          System.out.println(ex.getMessage());
      }
}
}

Problem is that when I create dbconnect object with simple java class's main method data is successfully written in database,but when I try to create dbconnect object from servlet it does not add data to the database. I use netbeans and have added mysql driver to the classpath. P.S. servlet is called by JSP file,which passes to servlet some html form parameters.

I suppose my question is clear and would like seeing comments from you.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Nika Tsogiaidze
  • 949
  • 14
  • 18

2 Answers2

1

Who wrote negative feedback on my question?

If this question was stupid or not appropriate why he could not answer it?

Finally after 7 hours of thinking and trying I found solution and I will write it in order someone also meets this problem in the future.

So the reason for the dbconnect class worked for simple java class and not for servlet is simple.Simple class automatically registers jdbc driver(in this case mysql driver) with the java application but servlet does not.Therefore I just had to write this line of code at the start of starting connection to the database:

Class.forName("com.mysql.jdbc.Driver");
Nika Tsogiaidze
  • 949
  • 14
  • 18
  • I have seen your question now and it's good that you have found out the solution yourself..The line by which you got your solution `Class.forName("")` one, it is the basic line while making database connection. Without this, you cannot connect to database whether you write your code in servlets or in jsp. It loads the `mysql` driver for connecting to the database – Java Enthusiast Jun 24 '14 at 07:33
  • Yes now I understand it,but it simple classes worked perfectly without this line,so I did not even think about changing code while searching for solution. – Nika Tsogiaidze Jun 24 '14 at 07:52
  • Now remember this, whenever you make database connection in java with mysql, where so ever it is, you are required to add this line otherwise you will not be able to connect to your database – Java Enthusiast Jun 24 '14 at 07:55
0

Hi there your code is working fine I tried with this

public class Dbconnect {
    Connection conn;

    public Dbconnect(){
        try{
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "welcome");
            String sql = "INSERT INTO student(student_id,student_name,class) VALUES(?,?,?)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setInt(1, 7);
            statement.setString(2, "nika1");
            statement.setString(3, "nika");
            int rowsInserted = statement.executeUpdate();
            if (rowsInserted > 0) {
                System.out.println("A new user was inserted successfully!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

The servlet-class :

public class Logic extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("name");
        Dbconnect con = new Dbconnect();
        try {
            PrintWriter out = response.getWriter();
            out.println("Inserted..");
        }
        catch (Exception e)
        {}
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

}

In web.xml :

    <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>main.myPack.Logic</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>s1</servlet-name>
        <url-pattern>/logic</url-pattern>
    </servlet-mapping>
SparkOn
  • 8,806
  • 4
  • 29
  • 34