簡體   English   中英

如果 DBNull 問題,則 ExecuteScalar

[英]ExecuteScalar if DBNull issue

我試圖像這樣處理 DbNull 異常:

string sql_com_sumcastka = "SELECT SUM(price) AS sumprice FROM kliplat WHERE akce='" + zakce.Text + "' AND year=" + year;
            SqlCommand sc2 = new SqlCommand(sql_com_sumprice, spojeni);
            spojeni.Open();

            if (sc2 != DBNull.Value)
            {
                int result = Convert.ToInt32(sc2.ExecuteScalar());
            }
            else
            {
                int result = 0;
            }
            spojeni.Close();

            string sql_com_update_sum = "UPDATE zajezd SET s_prijmy=@s_prijmy WHERE akce='"+zakce.Text+"' AND year="+year;
            SqlCommand sc3 = new SqlCommand(sql_com_update_sum,spojeni);

            sc3.Parameters.AddWithValue("@s_prijmy", result );
            spojeni.Open();
            sc3.ExecuteNonQuery();
            spojeni.Close();

但由於我不知道如何正確處理結果是否為 DBNull 我得到這個錯誤: Operator '"=' cannot be applied to operands of type system.Data.SqlClient.SqlCommand and System.Dbnull system.Data.SqlClient.SqlCommand Operator '"=' cannot be applied to operands of type system.Data.SqlClient.SqlCommand and System.Dbnull

當前上下文中不存在名稱“結果”

我的問題是這行代碼:

if (sc2 != DBNull.Value)
        {
            int result = Convert.ToInt32(sc2.ExecuteScalar());
        }
        else
        {
            int result = 0;
        }

謝謝你的幫助。

ExecuteScalar 不返回 DBNull(除非...,請閱讀下面的評論)而是 null 並且您需要測試 ExecuteScalar 的返回值而不是執行命令的 SqlCommand

   int sumOfPrice = 0;
   object result = sc2.ExecuteScalar();
   if(result != null)
       sumOfPrice = Convert.ToInt32(result);

來自 MSDN

ExecuteScalar 返回結果集中第一行的第一列,如果結果集為空,則返回空引用(在 Visual Basic 中為 Nothing)。

作為旁注,不要使用字符串連接來構建要傳遞到數據庫的命令文本。 你冒着 Sql 注入和解析錯誤的風險。 改用像這樣的參數化查詢

string sql_com_sumcastka = "SELECT SUM(price) AS sumprice FROM kliplat " + 
                           "WHERE akce=@zak AND year=@year";
SqlCommand sc2 = new SqlCommand(sql_com_sumprice, spojeni);
sc2.Parameters.AddWithValue("@zak", zakce.Text);
sc2.Parameters.AddWithValue("@year", year);

這是做到這一點的正確方法

var objResult = sc2.ExecuteScalar();

if (objResult != DBNull.Value && objResult != null )
{
    int result = (int)objResult; //you can just do a normal cast, "SUM(X)" returns a int.
}
else
{
    int result = 0;
}

在您的示例中,永遠不能將SqlCommandDBNull.Value進行比較。 聽起來您想要的是檢查執行標量調用的結果以查看它是否為空:

var result = sc2.ExecuteScalar();

if(result as DBNull == null)
{
    // value is not null, do processing
}

我知道答案遲了但這是我找到的最簡單的答案

SELECT (SUM(price),0) FROM kliplat 

如果結果為null ,它將被替換為0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM