如何使用Java Servlet在MySql中插入值

时间:2014-08-23 11:03:57

标签: servlets

我在这里添加完整代码。检查以下用于在MySql中插入值的代码。执行程序时,不插入值。

数据库datab.java

Statement st=null;
Class.forName("com.mysql.jdbc.Driver");
     Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root", "1234");
     st=con.createStatement();

Servlet代码

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

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

    String s = "http://localhost:" + request.getServerPort() + ""
            + request.getContextPath()+"/Emp";

String a,b,c,d,e;

    try {
         a=request.getParameter("t1");
        b=request.getParameter("t2");
         c=request.getParameter("t3");
          d=request.getParameter("t4");
          e=request.getParameter("t5");
         System.out.println(a);
        datab dt = new datab();

     dt.st.execute("insert into employee(eid,emp_name,emp_age,emp_desig,emp_salary) values(a,b,c,d,e)");

     response.sendRedirect(s);
     } catch(Exception ex){ex.printStackTrace();
        out.close();
    }          
} 

1 个答案:

答案 0 :(得分:2)

假设a,b,c,d,e都是字符串 替换

insert into employee(eid,emp_name,emp_age,emp_desig,emp_salary) values(a,b,c,d,e)

insert into employee(eid,emp_name,emp_age,emp_desig,emp_salary) 
values('"+a+"','"+b+"','"+c+"','"+d+"','"+e+"')

而不是像这样的东西

dt.st.execute

您不要让datab类返回connectionObject并使用该对象创建Statement对象并执行语句。

请停止使用Statement并利用类似这样的PreparedStatement

String query = "insert into employee(eid,emp_name,emp_age,emp_desig,emp_salary) 
    values(?,?,?,?,?)"
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, a);
statement.setString(2, b);
statement.setString(3, c);
statement.setString(4, d);
statement.setString(5, e);
statement.executeUpdate();