返回值和布尔值

时间:2018-12-01 19:08:56

标签: c# asp.net sql-server

我试图返回布尔查询单独查询的值,但我无法正确处理。除了搜索是否找到任何东西,我没有收到任何其他错误。值Subscriberkey从另一个类传递到该类中。我想到的任何更改都会破坏代码并添加类似的内容

if (var == null)
{ 
    return true;
}

return SubscriberQuery.LookupSubProfile(querysubscriber);

不起作用。

public static bool LookupSubProfile (SubscriberProfileQuery subscriber)
{
    try
    {
        var connString = "Server = Server\\SQLEXPRESS; initial catalog = Stuff; integrated security = True;";

        var query = "SELECT * FROM Subscriber WHERE SubscriberKey = '@SubscriberKey'";

        query = query.Replace("@SubscriberKey", subscriber.Subscriberkey);

        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();
            SqlCommand command = new SqlCommand(query, conn);
            command.ExecuteNonQuery();
            conn.Dispose();
            conn.Close();
        }

        return false; 
    }
    catch
    {
        return false;
    }

2 个答案:

答案 0 :(得分:5)

让我们尝试解决该代码中存在的所有问题:

  1. ExecuteNonQuery不适用于SELECT,因为这完全是查询。
  2. 该代码对SQL注入开放,需要参数。
  3. using语句已调用Dispose()的{​​{1}},因此这些都不是必需的。
  4. 只要返回找到的值,Close()(如果什么也没发现)就不需要返回bool,或者如果发生了则抛出异常。

所以:

null

答案 1 :(得分:1)

您可以通过两种方式做到这一点,

1。使用out参数并将其发送给Method作为参考:

public static bool LookupSubProfile (SubscriberProfileQuery subscriber,out int someValueToReturn)
{
    ...
    return true;
}

用法为(整数):

int result;
bool value = LookupSubProfile (subscriber,out int result);

2。您可以返回一个元组:

(bool, int) LookupSubProfile() 
{   
    //...        
    return ( true, 3);
}

您可以像这样使用它:

var (value, result) = LookupSubProfile();