c# - Avoid string concatenation for parameters when they are null
问题描述
In C# I have query like that:
string query = "SELECT * FROM product WHERE name = @name";
...
da.SelectCommand.Parameters.AddWithValue("@name", name);
if (price.HasValue)
{
query += " AND price = @price";
da.SelectCommand.Parameters.AddWithValue("@price", price.Value);
}
..
How to avoid if
statements? In above example I have only one parameter but in my code I have several parameters what is mean that I have several if
statements
解决方案
you can do it with SQL query without any IFs , something like :
string query = "SELECT * FROM product WHERE name = @name AND (@price IS NULL OR price = @price)";
推荐阅读
- amazon-web-services - 无法创建具有自动缩放功能的 Ec2 实例并将其注册到 ECS 集群
- python - 在python中,我如何获取网页中特定字符串之间的值
- node.js - 为什么Visual code unbound remote debug
- python - 如何在pyspark中将数据框行转换为IndexedRow?
- code-injection - os远程命令注入OWASP假警报?
- python - 在python类中解构和赋值的神奇方法
- webpack - 原始捆绑文件时webpack与静态关键字冲突
- azure - 我应该将 AzureWebApp 任务指向什么路径?
- c - 如何在 OpenSSL 中找到 EVP_MD、EVP_MD_CT 等的定义?
- sql - 限制顶部对列