C# - Connection.Execute が有効な整数を返さない

okwaves2024-01-25  8

この質問にはすでに答えがあります: 戻り値を指定してストアド プロシージャを呼び出す

(9 件の回答)

3 年前

に閉店しました。

SQL データベースにユーザーが挿入したニックネームと同じニックネームを持つレコードがあるかどうかを確認できるように、変数に数値を返そうとしていますが、connection.Execute は -1 を返し続けます。 私はWindowsフォームアプリをやっています

これは私のストアド プロシージャです:

ALTER PROCEDURE [dbo].[spPerson_GetPerson]
@NickName nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    select COUNT(*) from dbo.Person where NickName = @NickName
END

これは私の方法です:

public static bool IsUserUnique(PersonModel model)
    {
        using (IDbConnection connection = new SqlConnection(CnnString("MathemaKids")))
        {
            bool recordAlreadyExists = false;
            var p = new DynamicParameters();
            p.Add("@NickName", model.NickName);

            int numberOfUsersWithSelectedPassword = connection.Execute("dbo.spPerson_GetPerson",p, commandType: CommandType.StoredProcedure);

            if (numberOfUsersWithSelectedPassword > 0)
            {
                return true;
            }
            return recordAlreadyExists;
        }
    }

その理由を知っている人はいますか?



------------------------

ストアド プロシージャから返される値は 1 つだけです。

execute メソッドを使用する場合は、方向を戻り値として動的パラメータを設定し、以下のコードを使用する必要があります。

p.Add("@Result", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
connection.Execute("dbo.spPerson_GetPerson", p, commandType: CommandType.StoredProcedure);
int numberOfUsersWithSelectedPassword = p.Get<int>("@Result");

詳細についてはブログをお読みください。 https://csharp.hotexamples.com/examples/-/IDbConnection/Execute/php-idbconnection-execute-method-examples.html

別の解決策

Execute の代わりに ExecuteScalar を使用します。

SqlCommand cmd = new SqlCommand("dbo.spPerson_GetPerson", con);
cmd.Parameters.AddWithValue("@NickName", model.NickName);
int numberOfUsersWithSelectedPassword = Convert.ToInt32(cmd.ExecuteScalar());

2020 年 9 月 3 日 8:40 に回答

プルショタマン

プルショタマン

529

4

銀バッジ 4 個

16 個

銅バッジ 16 個

2

両方の解決策を試しました。あなたの解決策の最初のケースでは、Execute は常に 0 を返します。2 番目のケースでは、ExecuteScalar は次を返します。 "プロシージャまたは関数 spPersonal_GetPersonal はパラメータ "@NickName" を期待しています。供給されていないものそうでない。

– カステルム85

2020 年 9 月 3 日 9:47

@Purushothaman のおかげで、小さな変更を加えて最終的にこれを解決できました。ありがとうございました!

– カステルム85

2020 年 9 月 3 日 10:20

総合生活情報サイト - OKWAVES
総合生活情報サイト - OKWAVES
生活総合情報サイトokwaves(オールアバウト)。その道のプロ(専門家)が、日常生活をより豊かに快適にするノウハウから業界の最新動向、読み物コラムまで、多彩なコンテンツを発信。