2014-02-17 81 views
0

我正在從數據庫中進行搜索。用戶將輸入字符串。這個字符串將被轉換成數組,然後這個數組索引值將從表中檢查以找到匹配。 我正在使用循環遍歷數組查詢執行是在該循環中,它的罰款,但如果有多個索引來搜索它顯示最後索引搜索值。 我知道這不是一個正確的搜索方式。在一個查詢中從數據庫搜索多個數組索引值

我該怎麼做。

SqlConnection conOpen; 
string[] arrayList; 
protected void Page_Load(object sender, EventArgs e) 
{ 
    DataLayer datalayer = new DataLayer(); 
    conOpen = datalayer.connectionOpen(); 

    string myString = Request.QueryString["searchText"].ToString(); 
    char[] separator = new char[] { ' ' }; 
    arrayList = myString.Split(separator); 
    for (int i = 0; i <= arrayList.GetUpperBound(0); i++) 
    { 
     Response.Write(arrayList[i]); 

     string asd = arrayList[i]; 


     String arrayQuery = "Select * from tbl_products where product_name LIKE '%" + @asd + "%'"; 

     DataSet ds = new DataSet(); 
     SqlDataAdapter da = new SqlDataAdapter(arrayQuery, conOpen); 
     da.Fill(ds, "tbl_products"); 
     GridView1.DataSource = ds; 
     GridView1.DataBind(); 
    } 
} 

回答

0

我太清楚你最終的結果應該是什麼,但我會猜測。我想你所要求的是,你希望查詢搜索用戶放入輸入元素的每個搜索項目實例(用空格分隔),並將所有這些發現返回給你的GridView。好。所以我建議你循環「建立」你的sql語句,然後運行sql並在循環後(而不是期間)綁定數據。

另一個更重要的元素是,您應該確定參數化這些值,因爲它來自用戶輸入以防止SQL注入。請原諒任何錯別字(已晚)。

 DataLayer datalayer = new DataLayer(); 
     conOpen = datalayer.connectionOpen(); 

     string myString = Request.QueryString["searchText"].ToString(); 
     char[] separator = new char[] { ' ' }; 
     arrayList = myString.Split(separator); 
     StringBuilder arrayQuery = new StringBuilder(); 
     SqlCommand myCommand = new SqlCommand(); 

     for (int i = 0; i < arrayList.Length; i++) 
     { 
      if (i==0) 
      { 
       arrayQuery.Append("Select * from tbl_products where product_name LIKE @asd" + i); 
      } else{ 
       arrayQuery.Append(" OR product_name LIKE @asd" + i); 
      } 

      myCommand.Parameters.AddWithValue("@asd" + i, "%" + arrayList[i] + "%"); 
     } 

     myCommand.CommandText = arrayQuery.ToString(); 
     myCommand.Connection = conOpen; 
     DataSet ds = new DataSet(); 
     SqlDataAdapter da = new SqlDataAdapter(myCommand); 
     da.Fill(ds, "tbl_products"); 
     GridView1.DataSource = ds; 
     GridView1.DataBind(); 
+0

'索引在數組的界限之外'使用**的錯誤** –

+0

正確...複製了他的循環代碼。使用<。謝謝 –

+0

'關鍵字'LIKE'附近的語法不正確,你的代碼看起來不錯,但我不知道爲什麼它沒有顯示任何結果 –