美文网首页
2、返回插入的数据的ID

2、返回插入的数据的ID

作者: 鬼鬼812 | 来源:发表于2019-12-11 10:21 被阅读0次

pstm = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
设置为带返回ID
ResultSet rs = pstm.getGeneratedKeys();
通过rs.getInt(1)获得ID
下面为全部代码:

public static int executeUpdate(String sql, Object[] params){
        Connection con = null;
        PreparedStatement pstm = null;
        try{
            con = getCon();
            pstm = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            if(params != null && params.length > 0){
                for(int i = 0 ; i < params.length ; i++){
                    pstm.setObject(i+1, params[i]);
                }
            }
            int x = pstm.executeUpdate();
            ResultSet rs = pstm.getGeneratedKeys();
            if(rs.next()){
                return rs.getInt(1);
            }
            return x;
        }catch(Exception e){
            e.printStackTrace();
            return -1;
        }finally{
            close(null, pstm, con);
        }
    }

相关文章

网友评论

      本文标题:2、返回插入的数据的ID

      本文链接:https://www.haomeiwen.com/subject/obcogctx.html