Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在参数化查询中检查null?_C#_Ms Access 2007_Parameterized Query - Fatal编程技术网

C# 如何在参数化查询中检查null?

C# 如何在参数化查询中检查null?,c#,ms-access-2007,parameterized-query,C#,Ms Access 2007,Parameterized Query,我有一个如下所示的类,它在Access 2007中有一个对应的表 Class Product { public int ProductId { get;set; } public string ProductName { get;set; } public string ProductColor { get;set; } } 这是我用于将产品添加到数据库的方法 public

我有一个如下所示的类,它在Access 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)
}

我错过了什么明显的东西吗?在这些参数化查询中检查空值的最佳方法是什么?

使用空合并运算符如何


dh.AddInParam(cmd,“@productColor”,DbType.String,product.productColor??DbNull.Value)

使用空合并运算符如何

dh.AddInParam(cmd,“@productColor”,DbType.String,product.productColor??DbNull.Value)

运算符可能是解决方案

dh.AddInParam(cmd, "@productId", DbType.Int32, 
                    product.ProductId ?? (object)DBNull.Value); 
这要求dh.AddInParam的第三个参数为object数据类型(应该已经是这种方式)

对于传递给AddInParam的每个参数,这个要求可能都是正确的,所以解决这个问题的最佳方法是更改此方法的代码,以考虑传入的空值。(当然,如果您有源代码)

运算符可能是解决方案

dh.AddInParam(cmd, "@productId", DbType.Int32, 
                    product.ProductId ?? (object)DBNull.Value); 
这要求dh.AddInParam的第三个参数为object数据类型(应该已经是这种方式)


对于传递给AddInParam的每个参数,这个要求可能都是正确的,所以解决这个问题的最佳方法是更改此方法的代码,以考虑传入的空值。(当然,如果您有源代码)

尝试使用空合并运算符

尝试使用空合并运算符

是的,第三个参数是对象类型..我必须将您的解决方案更改为product.ProductId??(object)DBNull.Value开始工作..它显示“运算符”不能应用于“字符串”和“System.DBNull”类型的操作数。首先出现错误..用findigs更正了答案。谢谢,是的,第三个参数是对象类型。我必须将您的解决方案更改为product.ProductId??(object)DBNull.Value开始工作..它显示“运算符”不能应用于“字符串”和“System.DBNull”类型的操作数。首先出现错误..用findigs更正了答案。谢谢-