简体   繁体   中英

JDBC insert query does not update mysql database

The following code does not insert a row into the corresponding table. I have already tested the db connection and ran the query in the database, both of which have passed however when I add inputs via a .jsp form the values are still not inserting.

public class UserDao {

public String registerUser(User user){
    String username = user.getUsername();
    String email = user.getEmail();
    String password = user.getPassword();

    Connection con;
    con = DBConnection.createConnection();

    PreparedStatement preparedStatement;

    try{
        con.setAutoCommit(false);

        String query = ("INSERT INTO user (username, email, password, user_id) VALUES(?, ?, ?, ?)");
        preparedStatement = con.prepareStatement(query);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, email);
        preparedStatement.setString(3, password);
        preparedStatement.setString(4,null);

        int i = preparedStatement.executeUpdate();
        con.commit();
        preparedStatement.close();
        con.close();

        if(i !=0 ){
            return "SUCCESS";
        }
    }catch(SQLException e){
      throw new RuntimeException(e);

    }

    return "Something is wrong!";
}

}

For reference here is what my servlet class and .jsp file looks also like:

public class UserRegistrationServlet extends HttpServlet {

public UserRegistrationServlet(){}
/**
 * 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 {

    String userName = request.getParameter("username");
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    User user = new User();
    user.setUsername(userName);
    user.setEmail(email);
    user.setPassword(password);
    UserDao userDao = new UserDao();
    String userRegistered = userDao.registerUser(user);
    if(userRegistered.equals("SUCCESS")){
        request.getRequestDispatcher("test.jsp").forward(request, response);

    }else{
        request.setAttribute("error", userRegistered);
        request.getRequestDispatcher("/UserRegistration.jsp").forward(request, response);
    }
}

}

    <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register</title>
<script> 
function validate()
{ 
var username = document.form.username.value; 
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword= document.form.conpassword.value;
if (username==null || username=="")
{ 
alert("Full Name can't be blank"); 
return false; 
}
else if (email==null || email=="")
{ 
alert("Email can't be blank"); 
return false; 
}
else if(password.length<6)
{ 
alert("Password must be at least 6 characters long."); 
return false; 
} 
else if (password!=conpassword)
{ 
alert("Confirm Password should match with the Password"); 
return false; 
} 
} 
</script> 
</head>
<body>
<center><h2>Java Registration application using MVC and MySQL </h2></center>
<form name="form" action="UserRegistrationServlet" method="post" onsubmit="return validate()">
<table align="center">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" name="conpassword" /></td>
</tr>
<tr>
<td><%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register"></input><input
type="reset" value="Reset"></input></td>
</tr>
</table>
</form>
</body>
</html>

Not sure where the error in my code, so any advice will be very helpful. Thanks

Updates:

MySQL中的用户表

[![After throwing a runtime exception ][2]][2]

You're setting user_id to null and the database complains that the column must not be null . I assume that you haven't passed null to the statement you tested against the DB directly, so that you were setting an empty string instead (or the table is to set a default or automatically generated value in case it's missing).

If there is a default value or a autogenerated one, you can simply leave away user_id in your insert statement and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM