第一种:
String sql = "select studentname, age, phone, address, other from customer"
+ " where studentname like ? ";
pstmt = conn.prepareStatement(sql);
// 设定参数
pstmt.setString(1, "%" + customername + "%" );
// 获取查询的结果集
rs = pstmt.executeQuery();
第二种:
百分号直接写在sql语句中
String sql = "select customercode, customername, phone, address, relationman, other from customer"
+ " where customername like \"%\"?\"%\" ";
pstmt = conn.prepareStatement(sql);
// 设定参数
pstmt.setString(1, customername);
// 获取查询的结果集
rs = pstmt.executeQuery();
package com.examples.jdbc.o11_模糊查询;
import com.examples.jdbc.utils.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 借助自定义的jdbc工具类,完成jdbc模糊查询
*/
public class Test {
public static void main(String[] args) {
likelySearch();
}
/**
* 自定义jdbc工具类,实现模糊查询
*/
private static void likelySearch() {
//3个资源对象
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//1.自定义工具类,获取jdbc数据库连接对象
connection = DBUtils.getConnection();
//2.
String sql = "select * from tb_user where uname like ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "__");
resultSet = preparedStatement.executeQuery();
//3.
while(resultSet.next()){
int id = resultSet.getInt("id");
String uname = resultSet.getString("uname");
String upasswd = resultSet.getString("upasswd");
System.out.println("id: " + id + " uname: " + uname + " upasswd: " + upasswd);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//4.自定义工具类,关闭jdbc资源对象
DBUtils.close(connection, preparedStatement, resultSet);
}
}
}