2012-07-23 46 views
1

我有一個類如下所示,其具有相應的表中訪問2007年如何檢查參數化查詢中的空值?

Class Product 
{ 
    public int ProductId 
    { 
     get;set; 
    } 
    public string ProductName 
    { 
     get;set; 
    } 
    public string ProductColor 
    { 
     get;set; 
    } 
} 

這是我使用用於添加產品到數據庫中的方法。

public static void AddProduct(Product product) 
    { 
     con.Open(); 
     string strSql = @"INSERT INTO PRODUCTS (PRODUCTID,PRODUCTNAME,PRODUCTCOLOR) 
         VALUES(?,?,?)"; 
     IDbCommand cmd = con.CreateCommand(); 
     cmd.CommandText = strSql; 

     dh.AddInParam(cmd, "@productId", DbType.Int32, product.ProductId); 
     dh.AddInParam(cmd, "@productName", DbType.String, product.ProductName); 
     dh.AddInParam(cmd, "@productColor", DbType.String, product.ProductColor); 
     cmd.ExecuteNonQuery(); 
     con.Close() 
    } 

現在我不介意用戶是否輸入了一些空值。在那種情況下,我如何更新AddProduct方法? 來我心中唯一的情況下做一個空檢查像下面的每個參數..

if(product.ProductColor = null) 
{ 
    dh.AddInParam(cmd, "@productColor", DbType.String, DbNull.Value); 
} 
else 
{ 
    dh.AddInParam(cmd, "@ProductColor, DbType.String, product.ProductColor) 
} 

我失去了一些東西明顯?檢查這些參數化查詢中的空值的最佳方法是什麼?

回答

4

Null coalescing運營商可能是解決

dh.AddInParam(cmd, "@productId", DbType.Int32, 
        product.ProductId ?? (object)DBNull.Value); 

這需要dh.AddInParam的第三個參數是對象數據類型的(這應該已經是這樣)

也許這對於傳遞給AddInParam的每個參數都會有要求,所以解決此問題的最佳方法是更改​​此方法的代碼以解釋傳入的空值。(當然,如果您擁有ve源)

+0

是第三個參數是對象類型..我不得不改變你的soulution到product.ProductId ?? (對象)DBNull.Value得到工作..它顯示'運營商'??'不能適用於'string'和'System.DBNull'類型的操作數錯誤。 – vinayan 2012-07-23 10:04:31

+0

更正了與您的findigs的答案。謝謝- – Steve 2012-07-23 10:11:59

2

如何使用NULL合併運算符?

dh.AddInParam(cmd, "@productColor", DbType.String, product.ProductColor ?? DbNull.Value);

0

嘗試使用null合併運算符