这是用于将值插入数据库的servlet代码

时间:2014-01-29 14:32:06

标签: java jsp servlets

package car;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet(name = "detail", urlPatterns = {"/detail"})

public class detail extends HttpServlet {
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)

       throws ServletException, IOException, ClassNotFoundException, SQLException {

    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {

        String name=request.getParameter("name");

        String emailid=request.getParameter("emailid");

        int mobile=Integer.parseInt(request.getParameter("mobile"));  

        String carname=request.getParameter("carname");

        int regno=Integer.parseInt(request.getParameter("regno"));

        int manufacturingyear=Integer.parseInt(request.getParameter("manufacturingyear"));

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        Connection con=DriverManager.getConnection("jdbc:odbc:userdetail","","");

        Statement st=con.createStatement();

        st.executeUpdate("insert into userdetail (name,emailid,mobile,carname,regno,manufacturingyear) values('"+name+"','"+emailid+"','"+mobile+"','"+carname+"','"+regno+"','"+manufacturingyear+"',)");

        getServletContext().getRequestDispatcher("index.jsp").forward(request, response);

        out.println("<html>");

        out.println("<head>");

        out.println("<title>Servlet detail</title>");            

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

        out.println("<body>");

        out.println("<h1>FILL DETAILS</h1>");

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

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

    } catch (Exception e) { 
       e.printStackTrace();
    } finally {            
       out.close();
    }

}

值未将给定值插入数据库(userdetail)。在数据库字段中显示为空。

字段数据类型

名称文字

emailid文字

mobile Int

carname Text

regno Int

manufacturingyear Int

1 个答案:

答案 0 :(得分:0)

您必须提取一个保存在db中的方法,并将该方法放在另一个类中。然后将一个main方法添加到db专用类,并尝试从main方法(而不是从servlet)插入一行。

将表单读取与数据库持久性和应用程序逻辑混合是一种非常糟糕的做法:您在示例中有证据:没有服务器就无法测试您的应用程序,也无法理解问题出在何处