我正在使用 MySQL 开发 ASP.net 应用程序,并且有一个与存储过程返回值相关的问题。
这是我的存储过程:
CREATE DEFINER=`pcg`@`%` PROCEDURE `UpdatePreSellerProfile`(
IN UserID INT(11),
IN SellerImageID INT(11),
IN BusinessImageID INT(11),
OUT ProfileUpdated INT(1)
)
BEGIN
SET @Approved = 'APPROVED';
UPDATE user SET
SELLER_IMAGE_ID = COALESCE((SELECT IMAGE_ID FROM image_url WHERE IMAGE_USER_ID = UserID AND IMAGE_ID=SellerImageID),SELLER_IMAGE_ID),
SELLER_BUSINESS_LOGO_ID = COALESCE((SELECT IMAGE_ID FROM image_url WHERE IMAGE_USER_ID = UserID AND IMAGE_ID=BusinessImageID),SELLER_BUSINESS_LOGO_ID)
WHERE (USER_LOGIN_ID = UserID AND USER_PROFILE_STATUS = @Approved);
SET ProfileUpdated = ROW_COUNT();
END
当我使用以下 MySQL 脚本测试此代码时,如果没有更新,我总是得到 0 (@ProfileUpdated
)。
call UpdatePreSellerProfile(@UserID, @SellerImageID, @BusinessImageID ,@ProfileUpdated);
但是当我在 C# 代码中检查这一点时,它始终显示 1 (ProfileUpdated
)。
if (oMySQLConnecion.State == System.Data.ConnectionState.Open)
{
MySqlCommand oCommand = new MySqlCommand("UpdatePreSellerProfile", oMySQLConnecion);
oCommand.CommandType = System.Data.CommandType.StoredProcedure;
MySqlParameter sqlProfileUpdated = new MySqlParameter("@ProfileUpdated", MySqlDbType.VarString);
sqlProfileUpdated.Direction = System.Data.ParameterDirection.Output;
oCommand.Parameters.Add(sqlProfileUpdated);
oCommand.Parameters.AddWithValue("@UserID", UserID);
oCommand.Parameters.AddWithValue("@SellerImageID", oSeller.SellerImageID);
oCommand.Parameters.AddWithValue("@BusinessImageID", oSeller.BusinessLogoID);
oCommand.ExecuteNonQuery();
Int16 ProfileUpdated = Convert.ToInt16(oCommand.Parameters["@ProfileUpdated"].Value);
if (ProfileUpdated > 0) // <<-- Should be greater only if it is updated is sucessfull
{
oDBStatus.Type = DBOperation.SUCCESS;
oDBStatus.Message.Add(DBMessageType.SUCCESSFULLY_DATA_UPDATED);
}
else
{
oDBStatus.Type = DBOperation.ERROR;
oDBStatus.Message.Add(DBMessageType.ERROR_NO_RECORDS_UPDATED);
}
oMySQLConnecion.Close();
}
为什么 MySQL 脚本与 C# 代码之间存在差异?
最佳答案
除非您设置了 UseAffectedRows
连接字符串选项,否则它默认为 false
。 This means :
When
false
(default), the connection reports found rows instead of changed (affected) rows. Set totrue
to report only the number of rows actually changed byUPDATE
orINSERT … ON DUPLICATE KEY UPDATE
statements.
此外,来自documentation of the ROW_COUNT
function :
For
UPDATE
statements, the affected-rows value by default is the number of rows actually changed. If you specify theCLIENT_FOUND_ROWS
flag tomysql_real_connect()
when connecting to mysqld [ed. note: this is the same asUseAffectedRows
], the affected-rows value is the number of rows “found”; that is, matched by theWHERE
clause.
因此,存储过程中的 UPDATE user
语句将返回查询找到的行数,而不是实际更新的行数。
要解决此问题,可以:
- 在连接字符串中设置
UseAffectedRows=true;
;这可能会导致其他UPDATE
查询发生变化。 - 向
WHERE
子句添加更多条件,例如WHERE ... AND SELLER_IMAGE_ID != SellerImageID AND SELLER_BUSINESS_LOGO_ID != BusinessImageID
,以确保仅找到该行并在确实需要更改时进行更新。
关于c# - 为什么MySQL在C#代码中返回总是1,但在存储过程中测试时却不是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59701480/