函数中返回int的一些问题 [英] Some problem in function that return int

查看:81
本文介绍了函数中返回int的一些问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部,

我做了一个函数,该函数返回(int)中的表计数,并使用返回的int在文本框中显示.

我编写了该代码,但它始终返回(-1).有人可以告诉我错误在哪里吗?

hiii all,

I made a function that return a count of table in (int) and use that returned int to be displayed in a textbox.

I made that code but it always returns (-1). Anyone can tell me where the error is?

public Int64 bulidcount()
    {
        Int64 iQryValue;
        SqlConnection conn = new SqlConnection(connstr);
        SqlCommand cmd_save = new SqlCommand();
        cmd_save.Connection = conn;
        cmd_save.CommandType = CommandType.StoredProcedure;
        cmd_save.CommandText = "usp_test";
        try
        {
             conn.Open();
            iQryValue = cmd_save.ExecuteNonQuery();
            return iQryValue;
        }
        catch (Exception ex)
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
            return 1;
        }  
 
    }


Int64 iResult = bulidcount();
 txt_MobileCount.Text = iResult.ToString();

推荐答案

免责声明:这不是无意回答问题.

相反,这是一个关于更严重的错误的警告.

为什么当引发异常时代码返回1? 1表示错误吗?这是否意味着在iQryValue == 1时应将其视为错误?!

更重要的是,这是一种非常糟糕且不安全的做法,如代码示例中所示,它阻止异常的传播(除了极少数情况下,当没有其他选项时,例外).
在代码中,应将"return 1;"行替换为"throw;".它将重新引发相同的异常.
Disclaimer: this is not intended to answer a question.

Instead, this is a warning about a much more serious mistake.

Why the code returns 1 when exception is thrown? Does 1 indicate an error? Does it mean that when iQryValue == 1 it should be considers as an error?!

More importantly, this is a very bad and unsafe practice to block an exception from propagation as shown in the code sample (except pretty rare cases when there is no other options).
In the code, the line "return 1;" should be replaced with "throw;". It will re-throw the same exception.


尝试:

Try:

cmd_save.ExecuteScalar();



ExecuteNonQuery仅返回受影响的行数(执行存储过程之后),ExecuteScalar将返回存储过程的结果(无论可能如何).



ExecuteNonQuery only returns the number of rows affected (after carrying out whatever your stored procedure does), ExecuteScalar will return the result of your stored procedure (whatever that might be).


我想,您的逻辑错误就在这里:
cmd_save.ExecuteNonQuery();&调用StoredProcedure.

除此之外,您可能必须在SP中启用无计数" .删除.

ExecuteNonQuery:执行插入/更新/删除和删除操作.返回受影响的行数.详细信息此处 [此处类似的讨论 [
I guess, your logical error lies here:
cmd_save.ExecuteNonQuery(); & StoredProcedure called.

Adding to that, probably you must have enabled ''no count'' in SP. Remove it.

ExecuteNonQuery: Executes insert/update/delete & returns number of rows affected. Details here[^].

Just to add on, a similar discussion here[^].


这篇关于函数中返回int的一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆