【问题标题】:How to return default value when value is null or empty当值为空或为空时如何返回默认值
【发布时间】:2015-08-31 21:58:45
【问题描述】:

如果返回值为 null 或为空,如何使以下代码返回零。另外我怎样才能只返回数据表上的第一条记录

  private DataTable GetData(SqlCommand cmd)
        {
            gridoutofstock.DataBind();
            DataTable dt = new DataTable();
            String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["AhlhaGowConnString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                sda.Dispose();
                con.Dispose();
            }
        }

【问题讨论】:

  • 返回0?你的函数被定义为返回一个DataTable - 你不能返回0。您可能应该添加更多详细信息或澄清您的问题。
  • 这是我的 sql 命令,它只返回一个值 select sum(Quantity) from [dbo].Orderdetails 那么如何使用 insted 的数据表?
  • 请用详细信息编辑您的问题,不要将它们添加为 cmets - 这些可能会被读者忽略。
  • 听起来您在问“为什么我在需要 int 时使用 DataTable 作为返回类型” - 这有点难以解释...也许您正在寻找 @987654321 @ ?

标签: c# sqldataadapter


【解决方案1】:

您需要使用 SqlCommand.ExecuteScalar 而不是 SqlDataAdapter,您正在尝试检索单个标量值而不是 DataSet。

例子:

static int GetOrderQuantity()
        {
            int quantity = 0;
            string sql = "select sum(Quantity) from [dbo].Orderdetails ";
            using (SqlConnection conn = new SqlConnection("Your connection string"))
            {
                SqlCommand cmd = new SqlCommand(sql, conn);
                try
                {
                    conn.Open();
                    quantity = (int)cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    //Handle exception
                }
            }
            return quantity;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-20
    • 2017-08-03
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2020-07-17
    • 2022-12-13
    相关资源
    最近更新 更多