【发布时间】:2020-04-16 14:31:06
【问题描述】:
我和我的同事遇到了一个问题。我们有几个 SQL 查询作为字符串。这是一个例子:
public class Query
{
public static string CreditTransferId(string expectedValue, string table, int statusId, int messageTypeId, int destination103, int destination202, string StoreStatus202Id)
{
return $"SELECT top 1 Id from {table} where MessageId = '{expectedValue}' and FlowId=3 and StatusId={statusId} and MessageTypeId={messageTypeId} and " +
$" Destination103={destination103} and Destination202={destination202} and StoreStatus103Id is null and StoreStatus202Id {StoreStatus202Id}";
}
}
现在我们将它们作为字符串从 Query 类中的方法返回。我们想重构代码使其更干净,因为我们有一个方法包含超过 3 个参数,无论如何都很难使用。
你会怎么做呢?组织需要大量参数的 SQL 查询的最简洁方法是什么,就像我们在上面的代码中一样?我非常感谢任何可能改善我们代码当前状态的答案。
谢谢!
【问题讨论】:
-
SQL注入的风险极高。是的,这只是一个返回字符串的方法,但它对参数的有效性进行零检查,使用纯字符串连接并且没有正式的参数定义......它永远不会通过我工作的代码审查。
-
只是为了澄清:您应该考虑没有数量的有效性检查来保护您免受 SQL 注入;检查输入纯粹是为了查看它们是否在您的预期范围内;为了防止 SQL 注入,你绝对应该使用 parameters;如果您喜欢编写自己的 SQL,Dapper 是执行参数化查询的一种非常方便的方式
标签: c# sql .net coding-style code-cleanup