我正在使用一个使用大量内联 SQL 查询的 asp.net 网站...我想知道是否最好动态创建内联查询:
int i = 500;
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand com = new SqlCommand(conn);
...
com.CommandText = "select from table where column < @parameter";
...
}
或者有一个类来保存应用程序所需的所有查询。像这样:
class SqlQueries
{
private string query1 =
"select * from tblEmployees where EmployeeName = @EmployeeName";
private string query2 =
"select * from tblVacation where EmployeeName = @EmployeeName";
public string Query(string s)
{
string str = string.Empty;
switch (s)
{
case "query1":
str = query1;
break;
case "query2":
str = query2;
break;
}
return str;
}
}
谢谢!
最佳答案
我一天中使用了很多 ADO.NET 查询,而且我一直使用第一种方法。第二种方法是一个有趣的想法,但如果您在使用它的代码中的其他位置编辑这些查询可能会很麻烦。它还使查看查询在代码中的特定位置执行的操作变得更加困难。示例:
string sql = "Update User set age = @age where UserId = @UserId";
告诉开发者发生了什么,同时:
string sql = SqlQueries.Query("updateAge");
留下关于正在更新哪些表/列的问题。此外,对于第一个,您确切地知道需要添加哪些参数。
如果您在多个可能会改变事情的地方编写此查询
关于c# - 内联 SQL 查询的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12750000/