如果数据库中不存在值,如何在sql查询中返回错误消息

时间:2013-06-25 01:40:24

标签: c# sql

我有一个带有值的sql数据库。我想用我输入的值交叉检查它,如果数据库中不存在该值,程序将返回自定义错误消息。我该怎么做呢?

这是代码:

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
       if (dr != null)
       {
           if (dr.Read())
           {
               var student = new StudentParticulars
              {

                  StudentName = dr.GetString(1),
                  SClass = dr.GetString(2),
                  SNRIC = dr.GetString(3),
                  FixedAmount = dr.GetDouble(4),

              };
               studentList.Add(student);
           }
           return studentList;
       }

       else
       {
           if (dr == null)
           {
               var student = new StudentParticulars
               {
                   StudentName ="",
                   SClass = "",
                   SNRIC = "0",
               };
           }
           return studentList;
       }         
  }

1 个答案:

答案 0 :(得分:0)

假设您使用的是普通的ADO.NET,您可以选择以下几种方法:

  1. 您可以使用输出参数编写存储过程。然后,您可以在执行查询后获取输出参数值并进行检查。如果值不是您想要的值,则抛出异常。如果你需要在数据库中运行某种复杂的程序,你可能只想这样做。

  2. 您可以简单地获取sql查询的值,如:select some_value from some_table where some_condition = met。然后获取查询返回的值,如果不是您想要的则抛出异常。我假设你想要类似的东西:select count(*) from table where column = value;

  3. 执行查询后,您可以检查数据集中的行数。如果它为空,则抛出异常。

    if(dataTable.DataRows.Count == 0)
      throw new CustomException("Data not found");
    else
    {
      //process your data
      return somethingMeaninful;
    }
    

    或者,如果这个方法只是评估一个值是否存在, 做这样的事情:

    if(dataTable.DataRows.Count == 0)
      return false;
    else
    {
      //process your data
      return true;
    }
    

    或使用数据阅读器

    int processedRows = 0;
    
    while(reader.Read())
    {
      //do something with the data.
      processedRows++;
    }
    
    if(processedRows == 0)
      throw new CustomException("The result set was empty");
    

    为简单起见,我没有在此处添加连接处理,但您需要在finally块中关闭连接,或使用using块中的连接。