您當然需要更好的方式來構建您的查詢。 如果沒有一定的檢查或篩選措施,您不會直接接受用戶的輸入並將其放入您的查詢中。這會將你的應用程序暴露給sql注入。 使用SQL參數。 嘗試此鏈接作爲參考:http://www.dotnetperls.com/sqlparameter
例如:
using (SqlCommand command = new SqlCommand("Select * from tableBooks WHERE @Field LIKE @Value", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Field", Textbox1.Text)); // I do not recommend using a textbox and letting the user write anything. You have to limit his choices by the fields in your table. Use a dropdownlist and limit his choices by meaningful fields in your "tableBooks" table.
command.Parameters.Add(new SqlParameter("Value", Textbox2.Text));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//GET YOUR BOOK
}
}
請注意我的意見:
//我不建議用一個文本框,讓用戶寫東西的「關鍵詞」 。你必須根據表中的列來限制他的選擇。使用下拉列表並通過來自「tableBooks」表的有意義的選擇來限制他的選擇。
我不想說的太刻薄..但我肯定會挑在[tag:C#]和[tag:SQL]上打開一本書。你的最終查詢將毫無意義。 –
另外你應該查找SQL注入攻擊。編寫這樣的代碼會讓自己陷入一個很大的失敗。 –
使用存儲過程來搜索數據。 – Raghubar