缩短数据访问代码......这会有用吗?

时间:2012-12-11 15:32:49

标签: c# asp.net sqlcommand

我正在查询数据,如果数据不存在,我插入它。如果是的话,我会做点别的事情:

SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = '" + orderNo + "';", connection);
SqlDataReader checkHeadReader = checkHead.ExecuteReader(CommandBehavior.SingleRow);

if (!checkHeadReader.HasRows)
{
    checkHeadReader.Close();
    addHead.ExecuteNonQuery();
}

但是我想知道是否有更短的编码方式?下面的代码会起作用吗?

SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = ' + orderNo + "';", connection);

if(checkHead.ExecuteReader(CommandBehavior.SingleRow).HasRows)
    addHead.ExecuteNonQuery();
else //this order already exists
    Server.Transfer(@"~/Views/Error.aspx");

1 个答案:

答案 0 :(得分:3)

ExecuteScalar非常适用于此,例如

using (SqlCommand cmdCheck = new SqlCommand("Select Count(*) From Table Where Order_No = '" + orderNo + "'", connection))
{
    int nExists = (int)cmdCheck.ExecuteScalar();
    if (nExists==0) addHead.ExecuteNonQuery();
}