我將Web表單插入到數據庫中,因此使用參數化查詢。我有一個CheckBoxList。我怎樣才能迭代CheckBoxList,爲每一個檢查的事物(多對多)創建一個插入語句,並保持這個參數化和執行一舉?迭代上的參數化查詢
我現在有這個權利:
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.";
}
正如你可以看到它的未完成。有什麼建議麼?
每個選中的項目都需要爲一組'url,submitted,author'生成一個insert? – tzaman 2010-07-28 21:27:38
@tzaman:不,每個檢查的項目都需要創建一個像這樣的INSERT語句:'INSERT INTO phones_resources(phone_id,resource_id)VALUES(@phone_id,@resource_id);'。 – jeffcook2150 2010-07-28 21:29:35
好的。所以,給定一個'ListItem'你在哪裏得到相關的'phone_id,resource_id'? – tzaman 2010-07-28 21:31:14