SQL Server: Dynamic where-clause

前端 未结 3 2005
慢半拍i
慢半拍i 2020-12-02 01:56

Problem:

Ajax suggest-search on [n] ingredients in recipes. That is: match recipes against multiple ingredients.

For instance:

3条回答
  •  暖寄归人
    2020-12-02 02:40

    You could at least parametrize the where clausule to avoid SQL injection, something alike:

    using System.Data;
    using System.Data.SqlClient;
    using System.Text;
    
    class Foo
    {
        public static void Main ()
        {
            string[] parameters = {"salt", "water", "flower"};
            SqlConnection connection = new SqlConnection ();
            SqlCommand command = connection.CreateCommand ();
            StringBuilder where = new StringBuilder ();
            for (int i = 0; i < parametes.Length; i++)
            {
                if (i != 0)
                    where.Append (",");
                where.AppendFormat ("@Param{0}", i);
                command.Parameters.Add (new SqlParameter ("Param" + i, parameters [i]));
            }
        }
    }
    

提交回复
热议问题