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

标签 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;
       }         
  }

最佳答案

假设您使用的是普通 ole、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 block 中关闭连接,或者在using block 中使用连接。

关于c# - 如果数据库中不存在值,如何在sql查询中返回错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17287821/

相关文章:

SQL Server 2008 根据插入日期分区表

php - 在 PHP 中为 MATCH AGAINST 准备的语句不起作用

mysql - 将 ID 重置为 SQL 中的逻辑顺序

c# - 在 C# 中将形状放在图像前面

c# - Entity Framework : Separation of concerns

c# - 如何在一行 C# 3.0 中将 object[] 转换为 List<string>?

c# - ITextSharp 添加页码到合并的 pdf 中

mysql - 计算每天的加类时间

mysql - MySQL 中何时使用单引号、双引号和反引号

c# - 如何获取要在 MVC 2 中显示的位图图像