本文實例講述了java實現(xiàn)的連接數(shù)據(jù)庫及模糊查詢功能。分享給大家供大家參考,具體如下:
模糊查詢是比較常見的一種查詢方式,例如在訂單表中,包含有訂單的具體日期。如果要查詢某年某月的訂單信息,最好的方式就是使用模糊查詢。進行模糊查詢需要使用關(guān)鍵字LIKE。在使用LIKE關(guān)鍵字進行模糊查詢時,可以使用通配符"%",來代替0個或者多個字符,使用下劃線_來代表一個字符。
注釋:需要注意的是在使用LIKE的時候,后面的查詢條件需要加 ' ',英文狀態(tài)下的單引號引起來,不然報錯如下
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package com.ningmeng; import java.sql.*; public class Test07 { public static void main(String[] args) { // TODO Auto-generated method stub try { Class.forName( "com.mysql.jdbc.Driver" ); //加載數(shù)據(jù)庫驅(qū)動 System.out.println( "加載數(shù)據(jù)庫驅(qū)動成功" ); String url= "jdbc:mysql://localhost:3306/test" ;//聲明自己的數(shù)據(jù)庫test的url String user= "root" ; //自己的數(shù)據(jù)庫用戶名 String pass= "123456" ; //自己的數(shù)據(jù)庫密碼 //建立數(shù)據(jù)庫連接,獲得連接的對象conn Connection conn=DriverManager.getConnection(url,user,pass); System.out.println( "連接數(shù)據(jù)庫驅(qū)動成功" ); Statement stmt=conn.createStatement(); //創(chuàng)建一個Statement對象 String sql= "select * from users where username like '%別%' " ; //生成sql語句 ResultSet rs=stmt.executeQuery(sql); //執(zhí)行sql語句 int id,age,sex; String username,password; System.out.println( "id\t 用戶名\t 密碼\t 性別\t 年齡" ); while (rs.next()){ id=rs.getInt( "id" ); username=rs.getString( 2 ); password=rs.getString( "password" ); age=rs.getInt( 4 ); sex=rs.getInt( "age" ); System.out.println(id+ "\t" +username+ "\t" +password+ "\t" +sex+ "\t" +age); //輸出查詢結(jié)果 } System.out.println( "模糊查詢成功" ); conn.close(); //關(guān)閉數(shù)據(jù)庫連接 System.out.println( "關(guān)閉數(shù)據(jù)庫連接成功" ); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
運行結(jié)果:
希望本文所述對大家java程序設(shè)計有所幫助。
原文鏈接:https://www.cnblogs.com/biehongli/p/5989161.html