2012-09-28 66 views
2

搜索我想查詢從特定列一些關鍵字和打印所有與關鍵詞對應的列值,現在的問題是,如果我使用查詢MySQL數據庫的關鍵字中包含運營商

SELECT * FROM的候補技能,如%在技​​能C%,和不同的行是:

的Java,C,C++,HTML,CSS,淨豆,我的Eclipse

的Java,Asp.Net,Eclipse的

C,PHP,CSS,休眠

現在,它是所有的行作爲C是每一行中的子字符串,我試圖使用C%,而不是%C%,但只有第三行顯示,因爲它以C開頭,但我需要顯示所有行有「C」作爲另一個詞,我如何搜索整個世界,建議一段代碼。

import java.util.*; 
import java.sql.*; 
import java.io.*; 

public class TokensOfString 
{ 
    public static void main(String[] args) 
    { 
     String str; 
     String query = ""; 
     try 
     { 
      int i =0, cntToken =0; 
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
      System.out.println("Enter the keywords to be searched"); 
      str = br.readLine(); 
      StringTokenizer words = new StringTokenizer(str, ","); 
      cntToken = words.countTokens(); 
      //System.out.println("No. of Tokens = "+cntToken); 

      String token[]= new String[cntToken]; 

      while(words.hasMoreElements()) 
      { 
       token[i] = words.nextToken().trim(); 
       //System.out.println(token[i]); 
       i++; 
      } 
       //System.out.println(++i+" : "+words.nextElement().toString().trim());  

      query = "SELECT * from can_skills where skills like '"+ token[0] +"%'"; 
      // System.out.println("Query at 34 : "+query); 
      if(cntToken == 1) 
      { 
       query =""; 
       query = "SELECT * from can_skills where skills like '"+ str +"%'"; 
      } 
      if(cntToken > 1) 
      { 
       for(int j=1; j < cntToken; j++) 
       query = query + " or skills like '"+ token[j] +"%'"; 
      } 
      System.out.println("Query at 43 : "+query); 

      Connection con = null; 
      Class.forName("com.mysql.jdbc.Driver"); 
      String hostName = "localhost"; 
      String port = "3306"; 
      String userName = "root"; 
      String password = "root"; 
      con = DriverManager.getConnection("jdbc:mysql://" + hostName + ":" + port + "/prem", userName, password); 
      Statement statement= con.createStatement(); 
      ResultSet rs = statement.executeQuery(query); 
      while(rs.next()) 
      { 
       System.out.println(rs.getString(4)); 
      } 

     } 
     catch(ClassNotFoundException e){ System.out.println(e); } 
     catch(Exception ex){ System.out.println(ex); } 
    } 
} 

回答

0

在代替like表達使用正則表達式:

select * 
from Candidate 
where skills regexp '^C,| C,| C$' 

|裝置or^表示字符串的開始,而$表示結束。所以它會匹配字符串的開始,結束和中間的標記。請注意,第二個和第三個案例之前有空格。

在java中,如果我沒有說錯:

"SELECT * from can_skills where skills regexp '^" + token[0] + ",| " + token[0] + ",| " + token[0] + "$'"; 
+0

謝謝,它工作 – P3M