我有一个类如下所示,其具有相应的表中访问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)
}
我失去了一些东西明显?检查这些参数化查询中的空值的最佳方法是什么?
是第三个参数是对象类型..我不得不改变你的soulution到product.ProductId ?? (对象)DBNull.Value得到工作..它显示'运营商'??'不能适用于'string'和'System.DBNull'类型的操作数错误。 – vinayan 2012-07-23 10:04:31
更正了与您的findigs的答案。谢谢- – Steve 2012-07-23 10:11:59