2012-07-23 63 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合并运算符