为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕工程0101907 2022-08-03 10:54:40
下面的代码不会在相应的表中插入一行。我已经测试了数据库连接并在数据库中运行了查询,但是当我通过.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 */@Overrideprotected 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();不确定我的代码中的错误在哪里,所以任何建议都会非常有帮助。谢谢
查看完整描述

1 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

您正在设置为 ,但数据库抱怨该列不得为 。我假设您没有直接传递到针对数据库测试的语句,因此您设置了一个空字符串(或者表将设置默认值或自动生成的值,以防丢失)。user_idnullnullnull

如果存在默认值或自动生成的默认值,则只需在插入语句中省略即可,它应该可以正常工作。user_id


查看完整回答
反对 回复 2022-08-03
  • 1 回答
  • 0 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号