场景,测试下 prepareStatement 和 Statement 拼接 in 条件的情况。
prepareStatement 正常写法,执行成功
public static void main(String[] args) throws Exception{
Connection conn = JdbcUtils.getConn();
PreparedStatement pst = conn.prepareStatement("select * from emp where empno in (?)");
pst.setString(1, "7369");
ResultSet rs = pst.executeQuery();
while(rs.next()){
String username = rs.getString("ename");
System.out.println(username);
}
}
如果prepareStatement,想在参数中带有 () ,会报错
public static void main(String[] args) throws Exception{
Connection conn = JdbcUtils.getConn();
PreparedStatement pst = conn.prepareStatement("select * from emp where empno in ?");
pst.setString(1, "(7369)");
ResultSet rs = pst.executeQuery();
while(rs.next()){
String username = rs.getString("ename");
System.out.println(username);
}
}
报错: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 ''(7369)'' at line 1
测试 Statement 在参数中带 (),执行成功。
public static void main(String[] args) throws Exception{
Connection conn = JdbcUtils.getConn();
Statement sta = conn.createStatement();
String param = "(7499)";
ResultSet rs = sta.executeQuery("select * from emp where empno in "+param);
while(rs.next()){
String username = rs.getString("ename");
System.out.println(username);
}
}
类似的,在mybaits中 #{} 相当于 prepareStatement,所以不能在参数中拼接 ()符号。
${}可以在参数中拼接特殊符号。