如何检查列是否具有特定值

时间:2015-11-28 16:51:01

标签: c# asp.net sql-server

我有一个MS SQL数据库,其中有以下字段:

  • 引用号
  • businessid
  • 工人
  • LOCATIONNAME
  • 时间
  • 描述
  • 报价

使用相同的businessid可以有很多行,并且具有相同的refno,可以有很多行。但是使用相同的refno和businessid,只能有一行。现在可以有许多行具有相同的businessid,但我想检查这些businessid中是否存在特定的refno。我知道如何检查表中是否存在businessid。但我很困惑如何检查具有相同名称的businessid是否具有特定的refno。

string g = Session["businessid"].ToString();
string h = Session["referenceno"].ToString();
con.Open();
SqlCommand check = new SqlCommand("select * from quoted_price where businessid=@businessid", con);
check.Parameters.AddWithValue("@businessid", g);
SqlDataReader dr = check.ExecuteReader();        
if (dr.HasRows)
{
    con.Close();
}

1 个答案:

答案 0 :(得分:1)

您的代码存在一个主要问题。您没有正确处理实现IDisposable的对象。您需要使用using块或try/catch/finally模式,在finally块中处理清理。如果不这样做会导致连接断开,以后您可能会遇到奇怪的难以诊断的错误。对于您使用的任何类(特别是在需要存储或网络访问时),请始终检查它是否实现IDisposable

您还应该考虑何时在打开连接时创建SqlConnection vs。为什么在准备使用它之前打开连接?

此外,变量应充分描述它们包含的信息。避免使用无用的名称,例如gh

最后,您可以使用两个参数来检查您想要检查的条件。

string businessId = Session["businessid"].ToString();
string referenceNo = Session["referenceno"].ToString();    
bool hasRows = false;    

using(SqlConnection connection = new SqlConnection(parameters))
{
    using(SqlCommand checkCommand = new SqlCommand("select * from quoted_price where businessid=@businessid AND refno=@refno", connection))
    {
        checkCommand.Parameters.AddWithValue("@businessid", businessId);
        checkCommand.Parameters.AddWithValue("@refno", referenceNo);
        connection.Open();
        using(SqlDataReader dataReader = check.ExecuteReader())
        {
             hasRows = dataReader.HasRows;
        }                   
    }
}

请注意,不是试图用dataReader来做很多逻辑,而是从我得到我想要的东西,并存储我关心的值。这是因为我不想让连接打开超过必要的时间。