2013-07-02 39 views
1

我正在使用以下SQL查詢來搜索數據庫。使用關鍵字搜索訪問數據庫

string sql = "SELECT [identifier] FROM [information] WHERE [identifier] LIKE '" + identifier + "%'";

當我輸入「m」來搜索「微軟」時,它發現微軟,但如果我輸入「o」它沒有找到微軟。

我該如何更改SQL以便它找到包含該特定單詞的所有內容?

+0

小心SQL注入漏洞在這裏。 – pilotcam

回答

0

它不搜索字符串的原因Microsoft當您搜索字母o是因爲您的條件根據起始字符進行過濾。

這種情況,

... WHERE [identifier] LIKE 'o%' 

意味着..give我與角色o開頭的所有字符串。如果你想搜索一個字符串contains字符o,你應該用%%來包裝它。例如,

... WHERE [identifier] LIKE '%o%' 

一點題外話,你應該參數化值,以避免SQL Injection

試試這個代碼片段:

string connStr = "connection string here"; 
string content = string.Format("{0}{1}{0}", "%", identifier); 
string sqlStatement = "SELECT [identifier] FROM [information] WHERE [identifier] LIKE ?"; 
using (SqlConnection conn = new SqlConnection(connStr)) 
{ 
    using(SqlCommand comm = new SqlCommand()) 
    { 
     comm.Connection = conn; 
     comm.CommandText = sqlStatement; 
     comm.CommandType = CommandType.Text; 

     comm.Parameters.AddWithValue("@content", content); 

     try 
     { 
      conn.Open(); 
      // other codes 
     } 
     catch(SqlException e) 
     { 
      // do something with the exception 
      // do not hide it 
      // e.Message.ToString() 
     } 
    } 
} 

對於正確的編碼

  • 使用using語句正確的對象處理
  • 使用try-catch塊妥善處理異常
+0

我試過但不工作「SELECT [identifier] FROM [information] WHERE [identifier] LIKE'%」+ identifier +「%'」; –

+0

定義不起作用。 –

+0

它仍然不能搜索使用「O」,它僅適用於「M」 –

0
string sql = "SELECT [identifier] FROM [information] WHERE INSTR([identifier]," + identifier +") != 0 "; 

ACCESS function INSTR()