有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Out参数在MySQL中工作,但在JDBC中不工作,总是返回相同的值

这个过程在MySQL中运行良好,并返回正确的值,但在使用JDBC时,它总是返回1

在MySQL中,当我调用这个过程时,当行被更新时,我将得到1,当否时,我将得到0

在JDBC中,不管发生什么,它总是返回1

我尝试了不同的JDBC驱动程序,但没有结果,我也没有找到解释。当然,我们可以使用不同的代码来获得相同的结果,但是有人能解释为什么会发生这种情况吗

程序

CREATE DEFINER=`root`@`localhost` PROCEDURE `UPDATE_PARTICIPANT`(
IN 
p_id int(11),
p_first_name VARCHAR(45),
OUT
p_suceed INT(11)
)
BEGIN
    UPDATE `appdb`.`participants` 
    SET `id`=p_id,
    first_name = p_first_name
    WHERE `id`= p_id;
    SET p_suceed = ROW_COUNT();
END

JDBC

    Connection conn = null;
    try {
        conn =
                DriverManager.getConnection("jdbc:mysql://localhost/appdb?" +
                        "user=root&password=password&serverTimezone=UTC");
    } catch (SQLException ex) {
    }

    int id = 3;
    String firstName = "updatedName";

    CallableStatement cStmt = conn.prepareCall("{CALL UPDATE_PARTICIPANT(?,?,?)}");
    cStmt.setInt(1, id);
    cStmt.setString(2, firstName);
    cStmt.registerOutParameter(3,java.sql.Types.INTEGER);
    cStmt.execute();
    int outputValue = cStmt.getInt(3);
    System.out.println(outputValue);

谢谢

编辑:

为了更好地说明这个问题,我制作了一个短片:https://www.youtube.com/watch?v=x_WpngvO8o0&feature=youtu.be 伙计们,请关注为什么MySQL中的变量是正确传递的,但我们在JDBC中无法得到它:)

编辑2:

For UPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is the number of rows “found”; that is, matched by the WHERE clause.

这可能是原因,默认情况下,JDBC驱动程序会启用此选项


共 (1) 个答案

  1. # 1 楼答案

    This could be the cause, by default JDBC driver has [CLIENT_FOUND_ROWS] on.

    没错。根据MySQL Connector/J开发团队对JDBC规范的解释,UPDATE语句应该返回语句匹配的行数,而不是实际更改的行数

    如果我们希望ROW_COUNT()反映实际更改的行数则需要包含参数

    useAffectedRows=true
    

    在我们的JDBC连接URL中