JDBC 插入查询不更新 mysql 数据库

下面的代码不会在相应的表中插入一行。我已经测试了数据库连接并在数据库中运行了查询,但是当我通过.jsp形式添加输入时,值仍然没有插入。


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!";

}

}


作为参考,这是我的 servlet 类和.jsp文件的样子:


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();


不确定我的代码中的错误在哪里,所以任何建议都会非常有帮助。谢谢


慕工程0101907
浏览 195回答 1
1回答

慕斯王

您正在设置为 ,但数据库抱怨该列不得为 。我假设您没有直接传递到针对数据库测试的语句,因此您设置了一个空字符串(或者表将设置默认值或自动生成的值,以防丢失)。user_idnullnullnull如果存在默认值或自动生成的默认值,则只需在插入语句中省略即可,它应该可以正常工作。user_id
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java