java.sql.SQLException:无法在java servlet程序中使用executeQuery()发出数据操作语句

时间:2015-03-18 10:24:56

标签: java mysql servlets jdbc

public class CreateAccount extends HttpServlet 
{

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    Connection con=null;
    PreparedStatement pstm=null;
    PreparedStatement pstm1=null;

    PrintWriter pw=resp.getWriter();
    String name=req.getParameter("txt_name");
    String contact=req.getParameter("txt_contact");
    String email=req.getParameter("txt_email");
    String pin=req.getParameter("txt_pass");
    String address=req.getParameter("txt_address");
    String accType=req.getParameter("txt_accType");
    String gender=req.getParameter("radio_gender");
    String city=req.getParameter("txt_city");
    String state=req.getParameter("txt_state");

    String url="jdbc:mysql://localhost:3306/bankapp";
    String user="root";
    String dbpass="pass";


    try {
        Class.forName("com.mysql.jdbc.Driver");
        con=DriverManager.getConnection(url, user, dbpass);
        String sql="INSERT INTO AccountDetails VALUES(?,?,?,?,?,?,?,?,?,?,?)";
        pstm=con.prepareStatement(sql);
        pstm.setString(1, name);
        pstm.setString(2, contact);
        pstm.setString(3, email);
        pstm.setString(4, pin);
        pstm.setString(5, address);
        pstm.setString(6, accType);
        pstm.setString(7, gender);
        pstm.setString(8, city);
        pstm.setString(9, state);
        pstm.setString(10, null);
        pstm.setString(11, null);

        pstm.executeUpdate();

        String sql1="SELECT accNumber FROM AccountDetails WHERE email=?";
        pstm1=con.prepareStatement(sql1);
        pstm.setString(1, email);
        ResultSet rs=pstm.executeQuery();
        int accnum=0;
        while(rs.next()){
            accnum=rs.getInt("accNumber");
        }


        pw.write("<html><head>Dear "+name+" Thankyou For Registering With Us</br>");
        pw.write("Your Account Number Is :"+accnum+"</head></html>");
    } catch (ClassNotFoundException e) {

        e.printStackTrace();
    } catch (SQLException e) {

        e.printStackTrace();
        pw.write("<html><head>Oops Something Wrong With Our Database"+e+"</head></html>");
    }finally {
        try {
            pstm.close();
            //pstm1.close();
            con.close();
        } catch (SQLException e) {

            e.printStackTrace();
            pw.write("<html><head>Something Wrong With Connection"+e+"</head></html>");
        }
    }



}


}

我已经使用了MySQL数据库我已采用的列&#34; accNumber&#34;作为INT(10)和主键。 我使用了所有可能从结果集中获取值的东西,但我一次又一次地得到相同的错误。 请帮帮我盖伊。

1 个答案:

答案 0 :(得分:1)

就像名称暗示executeQuery()用于查询数据一样。对于插入和更新,您需要使用executeUpdate()

您的错误来自混淆pstm1pstm变量的简单错误。小心那段代码。