环境:
- C#
- Visual Studio 2012
- .NET Framework 3.5
嗨
我可以参数化 SQL Server 中的 where 子句吗?
在我的场景中,一旦输入 WHERE 子句字符串,应用程序会将其连接到查询的其他部分并在 SQL Server 中执行,然后返回结果。
例如,
- 用户输入“[CookingTime] < 30 且 [Cost] < 20”
- 应用程序创建查询“select [RecipeID] from [Recipes] where [CookingTime] < 30 and [Cost] < 20”并在 SQL Server 中执行。
- 应用程序将结果返回给用户。
出于安全原因,我想将整个 WHERE CLAUSE 作为参数。 但我不知道如何实现。
提前致谢。
最佳答案
This是如何做到的
string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
+ "WHERE CustomerID = @ID;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("@demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
关于c# - 在查询中参数化 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18524717/