package com.bjpowernode.jdbc; import java.sql.*; /** * 使用PreparedStatement做模糊查询 (重点是占位符的写法) */ public class 使用预编译进行模糊查询 { public static void main(String[] args) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //注册驱动 Class.forName("com.mysql.jdbc.Driver"); //连接数据库 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","******"); //获取预编译的数据库操作对象 //String sql = "select ename from emp where ename like '%?%'";//这样写是错误的,因为此时的?变成了一个普通字符。 String sql = "select ename from emp where ename like ?"; ps = conn.prepareStatement(sql); //传值 ps.setString(1,"%o%"); //处理查询结果集 rs = ps.executeQuery(); while(rs.next()){ System.out.println(rs.getString("ename")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
使用预编译进行模糊查询
于 2023-01-23 17:51:38 首次发布