c# - 在查询中参数化 WHERE 子句

标签 c# .net sql sql-server

环境:

  • 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/

相关文章:

c# - 哪里放try catch

sql - COALESCE 函数不会返回 CHAR(1)

c# - OpenGL闪烁问题

c# - Ninject 的 InSingletonScope() 创建多个实例

c# - 如何在 C# Windows 应用程序中锁定文本框(防止用户输入任何内容)(不是禁用它或使其不可见)

.net - Android Xamarin 应用程序中 System.Threading.Tasks.RangeWorker.FindNewWork 中的 NullReferenceException

c# - 使用 NavigateUrl 和 Eval() 的超链接。错误在哪里?

mysql - 按时间戳排序不正确

mysql - update 语句中having 子句的用法

c# - 将 ToolStripMenu 重新用于 ToolStrip 或 ContextMenuStrip?