dapper c# returns 行未找到受影响的行

dapper c# returns rows found not rows affected

我有一个简单的存储过程,它在 table 上进行更新。

CREATE PROCEDURE `test_v1`(
out v_changed_rows int
)
BEGIN
    update mytable
    set color = 'green'
    where id = 964291; 
    set v_changed_rows= ROW_COUNT();
END

从 mysql workbench 调用此存储过程会给出受影响的正确行(即第一次它将 return 1 然后 returns 0 因为我是用相同的值更新它,因此没有变化)

当我从 C# 调用此存储过程时出现问题

我尝试在 for 循环中调用此查询,并且每次 returns 1。 如何获取受查询影响的行,而不是查询找到的行? 谢谢。

ROW_COUNT()函数有这样的注释:

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.

虽然它说实际更改的行数默认为 return,但对于 MySql .Net 客户端,默认行为是 return WHERE 子句匹配的行数.这应该是由于 client_flag 参数的值传递给 mysql_real_connect.

您可以通过在连接字符串中将 UseAffectedRows 显式设置为 True 来更改此行为:

server=localhost;user id=test;password=test;database=test;UseAffectedRows=True

我试过了,它在 ADO.NET 和 Dapper 上都运行良好。

您可以在存储过程中使用 RETURN @@ROWCOUNT 在你的方法中做这样的事情:

var dynamicParameters = new DynamicParameters();
dynamicParameters.Add("@UpdatedCounter", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
var result = await _connection.ExecuteAsync("sp_Update", dynamicParameters, commandType: CommandType.StoredProcedure);
int updatedCounter = dynamicParameters.Get<int>("@UpdatedCounter");
return updatedCounter;