楔子

JDBC是Java对各种数据库的一个简单的封装,这边文章不是分享如何进行增删改查,而是说一个小的细节。使用MySQL删除时,无论表中是否有数据,都不会报错。

细节

举个例子

假设现在我的数据表中是空的。数据库进行delete from user where id = 1操作会返回Affected rows: 0, Time: 0.000000s,这样,我们在JDBC中通过execute方法就没法判断是否删除成功。

解决方案

使用executeUpdate()来代替execute()

executeUpdate

executeUpdate()的返回值是int类型,返回执行SQL语句影响的行数。这样我们只要判断返回值是否大于0即可。

举例代码

public static boolean delete(User u) {
        Connection conn = MysqlConnection.getConnection();
        try {
            String sql = "delete from user where id =?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setObject(1, u.getId());
            return ps.executeUpdate() != 0;
        } catch (SQLException e) {
            System.out.println(e + "> in User.delete");
            return false;
        }
    }
Last modification:July 17th, 2019 at 12:33 pm
如果我的文章对你有用,请随意赞赏,不要白嫖哦~