Java-JDBC使用PreparedStatement防SQL注入

Sql注入问题解决方案:使用PreparedStatement,具体代码如下:

    /**
     * 根据传入的用户名与密码查找用户
     * @author wei.luo
     * @createTime 2011-12-28
     * @param String name 用户名
     * @param String password 密码
     * @return User 返回查找到的用户
     */
    public User getByNameAndPassword(final String name,final String password) throws DaoExceptions {
        final User user=new User();
        final String sql="select * from users where user_name=? and user_pass=?";
        PreparedStatementCreator psc = new PreparedStatementCreator (){
            public PreparedStatement createPreparedStatement(Connection con)
                    throws SQLException {
                PreparedStatement ps=null;
                ps = con.prepareStatement(sql);
                ps.setString(1, name);
                ps.setString(2, password);
                return ps;
            }
        };
        this.getJdbcTemplate().query(psc, new RowCallbackHandler(){
            public void processRow(ResultSet rs) throws SQLException {
                user.setUserId(rs.getString("user_id"));
                user.setUserInfo(rs.getString("user_info"));
                user.setUserAddDate(rs.getDate("user_add_date"));
                user.setUserLevel(rs.getInt("user_level"));
                user.setUserName(rs.getString("user_name"));
                user.setUserPassword(rs.getString("user_pass"));
            }
        });
        return user;
    }

版权所有,转载请注明出处 luowei.github.io.