update sql statement with unknown name/amount of params

后端 未结 3 1671
礼貌的吻别
礼貌的吻别 2021-01-16 07:12

I have a classic ASP site, that I am slowly upgrading. I would like to create a function to securely update a SQL database without specifying parameters man

3条回答
  •  孤城傲影
    2021-01-16 08:16

    I'm not sure I fully understand what you're trying to do, but this might be close to what you're looking for. You can create an arbitrarily long list of parameters and respective values, then build the corresponding UPDATE dynamically from that list.

    //set up SqlCommand
    SqlCommand UpdateCmd = new SqlCommand();
    UpdateCmd.Connection = conn;
    
    //build your dictionary (probably happens elsewhere in your code)
    Dictionary parameters = new Dictionary();
    parameters.Add("col1", "col1 value");
    parameters.Add("col2", 42);
    parameters.Add("col3", DateTime.Now);
    
    //build a command string and add parameter values to your SqlCommand
    StringBuilder builder = new StringBuilder("UPDATE sometable SET ");
    foreach(KeyValuePair parameter in parameters) {
        builder.Append(parameter.Key).Append(" = @").Append(parameter.Key).Append(",");
        UpdateCmd.Parameters.AddWithValue("@" + parameter.Key, parameter.Value);
    }
    builder.Remove(builder.Length - 1,1);
    
    //set the command text and execute the command
    UpdateCmd.CommandText = builder.ToString();
    UpdateCmd.ExecuteNonQuery();
    

提交回复
热议问题