返回受 Java 中 SQL UPDATE 语句影响的行数

发布于 2024-08-27 13:16:53 字数 282 浏览 5 评论 0原文

我正在使用 MySQL 数据库并通过 Java 访问它。

PreparedStatement prep1 = this.connection.prepareStatement(
        "UPDATE user_table 
        SET Level = 'Super' 
        WHERE Username = ?");
prep1.setString(1, username);

上面的更新语句工作正常,但是我想获取受此语句影响的行数。请问这可能吗?

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

PreparedStatement prep1 = this.connection.prepareStatement(
        "UPDATE user_table 
        SET Level = 'Super' 
        WHERE Username = ?");
prep1.setString(1, username);

The update statement above works fine however I'd like to get the number of rows affected with this statement. Is this possible please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

怎樣才叫好 2024-09-03 13:16:53

Statement.executeUpdate()execute() 后跟 getUpdateCount() 将返回匹配的行数,根据 JDBC 规范,未更新。如果您想要更新的计数,可以将 useAffectedRows=true 指定为 非标准 URL 选项。更多信息请参见此处

Statement.executeUpdate() or execute() followed by getUpdateCount() will return the number of rows matched, not updated, according to the JDBC spec. If you want the updated count, you can specify useAffectedRows=true as a non-standard URL option. More information is available here.

眼泪淡了忧伤 2024-09-03 13:16:53

Calling executeUpdate() on your PreparedStatement should return an int, the number of updated records.

再浓的妆也掩不了殇 2024-09-03 13:16:53
  1. 首先,使用以下构造函数准备“PreparedStatement”对象:

    PreparedStatement pStmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    //这里变量'sql'是你的查询(“UPDATE user_table SET Level = 'Super' WHERE Username = ?”) 
    
  2. 然后,将参数设置为“pStmt”。在这种情况下:

    prep1.setString(1, 用户名);
    
  3. 最后,执行Update并获取受影响的行作为整数

    intaffectedRows = pStmt.executeUpdate();
    
  1. First of all, prepare the 'PreparedStatement' object using below constructor:

    PreparedStatement pStmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    //here variable 'sql' is your query ("UPDATE user_table SET Level = 'Super' WHERE Username = ?") 
    
  2. Then, set your argument to 'pStmt'. In this case:

    prep1.setString(1, username);
    
  3. Finally, executeUpdate and get affected rows as an integer

    int affectedRows = pStmt.executeUpdate();
    
林空鹿饮溪 2024-09-03 13:16:53

现在看看另一个类似的情况,如果确实发生了变化,我只想做额外的工作,我认为最平台中立的方法是更改​​查询以排除设置字段匹配的情况:

UPDATE user_table SET Level = 'Super' WHERE Username = ? AND Level <> 'Super'

Looking at this just now for another similar situation, where I only want to do additional work if something really changed, I think the most platform neutral way to do it would be to alter the query to exclude the case where the set fields match:

UPDATE user_table SET Level = 'Super' WHERE Username = ? AND Level <> 'Super'
胡渣熟男 2024-09-03 13:16:53

可以使用 SQL%ROWCOUNT (对于 ORACLE) 或 @@ROWCOUNT(对于 SQL SERVER) 返回受 SQL 更新影响的行数

注意:为了返回更新、删除等的行数。我们必须使用 OUT存储过程中的参数将存储更新、删除的行数等。

  1. 要获取更新、删除的行数等。我们必须使用
    Java 中的 registerOutParameter 方法

  2. 将更新或删除的行数等存储到其中之一
    存储过程中的 OUT 参数我们必须设置它的类型
    在执行命令之前在我们的脚本中添加参数。 (如果是
    更新或删除它将是数字)

  3. 命令执行后,存储更新或删除的值
    行放入变量(可以是新变量或变量
    通过调用该参数的索引可在类等中使用...)
    (例如:A=cs.getInt(3) 如果存储过程中的 OUT 参数是
    第二个参数)

  4. 现在,该变量的值为已更新或已删除的行
    (ieA=10)

存储过程示例

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;

java 脚本示例

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) {
}

}
}

注意:executeUpdate() 不返回更新或删除的行数。它只是返回0或1。

  1. 0--执行失败
  2. 1--执行成功

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
罗罗贝儿 2024-09-03 13:16:53

当您运行查询时会返回该数字:

int rows = prep1.executeUpdate(); 
System.out.printf("%d row(s) updated!", rows); 

That number is returned when you run the query:

int rows = prep1.executeUpdate(); 
System.out.printf("%d row(s) updated!", rows); 
夜深人未静 2024-09-03 13:16:53

如果需要知道有多少行会受到影响而不执行它,则必须首先运行 SELECT 语句。

If it is necessary to know how many rows will be affected without executing it, you will have to run a SELECT statement first.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文