java的PreparedStatement中使用like时的问题
SQL:select * from students where name like '%tommy%';
正常的sql如上,是可以直接执行的,
那放到java的P热怕热的Statement中就应该是:
//同时把tommy改成通配符?
PreparedStatement pstmt1 = conn.prepareStatement("select * from student where name like '%?%'");
pstmt1.setString(1,"tommy");//这里居然不通过
解决方法一:使用拼接字符串
PreparedStatement pstmt1 = conn.prepareStatement("select * from student where name like '%"+tommy+"%'");
解决方法二:灵活变通(其实就是通配符?不能放在''单引号中)
PreparedStatement pstmt1 = conn.prepareStatement("select * from student where name like ?");
pstmt1.setString(1,"%"+"tommy"+"%");