Return number of rows affected by SQL UPDATE statement in Java

后端 未结 7 1940
花落未央
花落未央 2020-12-30 20:26

I\'m using a MySQL database and accessing it through Java.

PreparedStatement prep1 = this.connection.prepareStatement(
        \"UPDATE user_table 
                


        
7条回答
  •  粉色の甜心
    2020-12-30 20:33

    The number of rows affected by SQL Update can be returned using SQL%ROWCOUNT (For ORACLE) or @@ROWCOUNT(FOR SQL SERVER)

    Note: In order to return the number of rows updated, deleted, etc.. we have to use OUT Parameter in Stored Procedure which will store the number of rows updated,deleted etc..

    1. To get the number of rows updated,deleted etc.. we have to use registerOutParameter method in Java

    2. To store the number of rows updated or deleted etc.. into one of the OUT parameter in stored procedure we have to set the type of that parameter in our script before executing the command. (In case of Update or delete it will be NUMERIC)

    3. Once the command is executed, store the value of updated or deleted rows into the variable (It can be new variable or variables available in class etc..) by calling the index of that parameter (for ex: A=cs.getInt(3) if the OUT parameter in stored procedure is 2nd parameter)

    4. Now, the variable has the value of Updated or deleted rows (i.e.A=10)

    Example for Stored porcedure

    Function demo( A varchar2(10), B OUT NUMBER)RETURN NUMBER IS EXIST_LP NUMBER;
    BEGIN
    UPDATE demo_temp SET name=A where name="ABC";
    B:=SQL%ROWCOUNT -- total number of rows updated
    RETRUN EXIST_LP;
    END demo;
    

    Example for java script

    public void update(demo demo){
    int rowCount = 0;
    Connection conn = null;
    CallableStatement cs = null;
    try{
    InitialContext ctx = new InitialContext();
    DataSource ds = (DataSource) ctx.lookup("your data source path");
    conn = ds.getConnection();
    cs = conn.prepareCall("BEGIN ? :=demo_dbp.demo(?,?) ); END;"); // stored proc
    cs.registerOutParameter(1, Types.INTEGER);
    cs.setString(2, "XYZ");
    cs.registerOutParameter(3, Types.NUMERIC);
    rowCount=cs.execcuteUpdate();
    demo.setUpdateCount(cs.getInt(3));
    } catch (SQLException exc) {
      throw new DaoException("An SQL Exception has occurred.", exc);
    } catch (NamingException ne) {
      throw new DaoException("A Naming Exception has occurred.", ne);
    } catch (Exception e) {
      throw new DaoException("An Exception has occurred", e);
    } finally {
    
      try {
                if (cs != null) {
                    cs.close();
                }
    } catch (SQLException ex1) {
    }
    try {
                if (conn != null) {
                    conn.close();
                }
    } catch (SQLException ex) {
    }
    
    }
    }
    

    Note: executeUpdate() doesn't return the number of rows updated or deleted. It just returns 0 or 1.

    1. 0--Execution Failed
    2. 1--Execution Success

提交回复
热议问题