1:模糊查詢是比較常見的一種查詢方式,例如在訂單表中,包含有訂單的具體日期。如果要查詢某年某月的訂單信息,最好的方式就是使用模糊查詢。進行模糊查詢需要使用關鍵字LIKE。在使用LIKE關鍵字進行模糊查詢時,可以使用通配符"%",來代替0個或者多個字符,使用下划線_來代表一個字符。
注釋:需要注意的是在使用LIKE的時候,后面的查詢條件需要加 ' ',英文狀態下的單引號引起來,不然報錯如下
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%別%' at line 1
1 package com.ningmeng; 2 3 import java.sql.*; 4 5 public class Test07 { 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 try { 10 Class.forName("com.mysql.jdbc.Driver");//加載數據庫驅動 11 System.out.println("加載數據庫驅動成功"); 12 String url="jdbc:mysql://localhost:3306/test";//聲明自己的數據庫test的url 13 String user="root";//自己的數據庫用戶名 14 String pass="123456";//自己的數據庫密碼 15 //建立數據庫連接,獲得連接的對象conn 16 Connection conn=DriverManager.getConnection(url,user,pass); 17 System.out.println("連接數據庫驅動成功"); 18 Statement stmt=conn.createStatement();//創建一個Statement對象 19 String sql="select * from users where username like '%別%' ";//生成sql語句 20 ResultSet rs=stmt.executeQuery(sql);//執行sql語句 21 int id,age,sex; 22 String username,password; 23 System.out.println("id\t 用戶名\t 密碼\t 性別\t 年齡"); 24 while(rs.next()){ 25 id=rs.getInt("id"); 26 username=rs.getString(2); 27 password=rs.getString("password"); 28 age=rs.getInt(4); 29 sex=rs.getInt("age"); 30 System.out.println(id+"\t"+username+"\t"+password+"\t" 31 +sex+"\t"+age);//輸出查詢結果 32 } 33 System.out.println("模糊查詢成功"); 34 conn.close();//關閉數據庫連接 35 System.out.println("關閉數據庫連接成功"); 36 } catch (ClassNotFoundException e) { 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 } catch (SQLException e) { 40 // TODO Auto-generated catch block 41 e.printStackTrace(); 42 } 43 44 } 45 }