简体   繁体   English

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

[英]How do I check for null in parameterized queries?

I have a class as shown below which has a corresponding table in Access 2007 我有一个如下所示的类,在Access 2007中有一个对应的表

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

this is the method i use for adding product to database. 这是我用于将产品添加到数据库的方法。

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()
    }

Now I do not mind if the user entered some null values. 现在我不在乎用户是否输入了一些空值。 In that case how can i update the AddProduct method? 在这种情况下,如何更新AddProduct方法? The only case coming to my mind is doing a null check for each parameter like below.. 我想到的唯一情况是对每个参数进行空检查,如下所示。

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

Am i missing something obvious? 我缺少明显的东西吗? What would be the best method for checking nulls in these parameterized queries? 在这些参数化查询中检查空值的最佳方法是什么?

Null coalescing operator could be the solution 空合并运算符可能是解决方案

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

This requires the third parameter of dh.AddInParam to be of object datatype (It should already be this way) 这要求dh.AddInParam的第三个参数具有对象数据类型(应该已经是这种方式)

Probably this requirement will be true for every parameter you pass to AddInParam, so the best way to solve this problem is changing the code of this method to account for null values passed in. (Of course, if you have the source) 对于传递给AddInParam的每个参数,此要求可能都是正确的,因此解决此问题的最佳方法是更改​​此方法的代码以考虑传入的空值。(当然,如果有源代码)

如何使用NULL合并运算符?

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

尝试使用空合并运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM