迭代的参数化查询

时间:2010-07-28 21:19:48

标签: c# tsql parameterized

我正在将一个Web表单插入到数据库中,因此使用参数化查询。我有一个CheckBoxList。我如何迭代CheckBoxList,为每个被检查的东西(多对多)创建一个insert语句,并保持这个参数化并一举执行?

我现在有这个:

string query = "INSERT INTO resources (url, submitted_by, author_name) VALUES (@url, @submitted_by, @author_name);";
foreach (ListItem li in CheckBoxList1.Items)
    {
        if (li.Selected = true)
        {
            query += "; INSERT INTO ";
        }
    }
    SqlCommand cmd = new SqlCommand(query, conn);
    cmd.Parameters.AddWithValue("@url", TextBox1.Text);
    cmd.Parameters.AddWithValue("@submitted_by", TextBox2.Text);
    cmd.Parameters.AddWithValue("@author_name", TextBox3.Text);

    try
    {
        conn.Open();
        cmd.ExecuteNonQuery();
        Label1.Text = "Added to database.";
    }

你可以看到它未完成。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ为集合中的每个项生成唯一的命名参数,然后在以后添加关联的值:

var builder = new StringBuilder();
var listParams = CheckBoxList1.Items
                     .Where(li => li.Selected)
                     .Select(li, idx => new 
                     {
                         PhoneString = String.Format("@phone_id{0}", idx),
                         PhoneValue = GetPhoneId(li),
                         ResourceString = String.Format("@resource_id{0}", idx),
                         ResourceValue = GetResourceId(li)
                     };
foreach (var param in listParams)
{
    builder.AppendFormat("INSERT INTO phones_resources (phone_id, resource_id) 
                          VALUES ({0}, {1});", 
                          param.PhoneString, param.ResourceString);
}
SqlCommand cmd = new SqlCommand(builder.ToString(), conn);
foreach (var param in listParams)
{
    cmd.Parameters.AddWithValue(param.PhoneString, param.PhoneValue);
    cmd.Parameters.AddWithValue(param.ResourceString, param.ResourceValue);
}

我假设您可以从任何给定的phone_id, resource_id获得关联ListItem的某种方式 - 您可以将其插入我放置占位符Get___功能的位置。

注意:切换到StringBuilder - 这比使用重复+=构建字符串要好得多。

相关问题