这两个占位符,#预编译后设置参数,#{}会被参数替换,$ 是sql与参数直接拼接,容易sql注入。
变量直接替换一般使用$,例如in(${xxx}),下面看一下源码层面怎么实现的。
一:#{}的替换
#{} 的替换就是jdbc预编译后的替换占位符 ?
/** * 执行查询操作 * * @param sql * @param list * @throws SQLException */ public static void executeQuery(String sql, List<Integer> list) throws SQLException { PreparedStatement preparedStatement = getPreparedStatement(sql); preparedStatement.setInt(1, list.get(0)); preparedStatement.setInt(2, list.get(1)); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String name = resultSet.getString("name"); System.out.println(name); } }
这时simpleExecutor类的doQuery方法:
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { Statement stmt = null; try { Configuration configuration = ms.getConfiguration(); StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); stmt = prepareStatement(handler, ms.getStatementLog()); return handler.<E>query(stmt, resultHandler); } finally { closeStatement(stmt); } }
创建PrepareStatement语句:
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException { Statement stmt; Connection connection = getConnection(statementLog); stmt = handler.prepare(connection); handler.parameterize(stmt); return stmt; }
PrepareStatementHandler的parameter方法:
public void parameterize(Statement statement) throws SQLException { parameterHandler.setParameters((PreparedStatement) statement); }
设置非空参数:
和上面jdbc设置参数的方式是一样的:
原文:https://www.cnblogs.com/warrior4236/p/13145132.html