今天遇到一个很纠结的问题,就是在预处理的sql语句中写模糊查询,第一种写法不对,第二种写法就对郁闷,不过总算也解决了,在此贴出来和大家共享下。
错误的
String sql="select s1.empno,s1.ename,s2.ename,s1.job,s1.hiredate,s1.sal,s1.comm,dname,loc,s1.deptno " +
"from emp s1,emp s2,dept " +
" where dept.deptno=s1.deptno and s2.empno=s1.mgr " +
" and s1.deptno=? and s1.ename like '%'+?+'%'";//联表查询,s1和s2是自查询
pst=conn.prepareStatement(sql);
pst.setInt(1,deptno);
pst.setString(2,name);//模糊查询 错误的写法,具体为什么我也不知道
rst=pst.executeQuery();
正确的
String sql="select s1.empno,s1.ename,s2.ename,s1.job,s1.hiredate,s1.sal,s1.comm,dname,loc,s1.deptno " +
"from emp s1,emp s2,dept " +
" where dept.deptno=s1.deptno and s2.empno=s1.mgr " +
" and s1.deptno=? and s1.ename like ?";//联表查询,s1和s2是自查询
pst=conn.prepareStatement(sql);
pst.setInt(1,deptno);
pst.setString(2,"%"+name+"%");//模糊查询 正确的写法
rst=pst.executeQuery();