拼接可用于in查询字符串

组件功能:

将一个可遍历的对象中的数据拼接为可用于sql中进行in查询的字符串

注:

当前方法还无法进行数组遍历

/**
 * 组件:拼接参数
 * 拼接好的样式为:(1,2,3....)
 * @param t 包含参数的列表
 * @param <T>实现Iterable的接口的类型
 * @return 拼接好的字符串
 */
protected  <T extends Iterable> String joinParameter(T t){
    //参数判空
    if(t == null){
        return null;
    }else {

        //参数字符串暂存区
        StringBuffer tempBuffer = new StringBuffer('(');

        //使用迭代器遍历列表
        Iterator iterator = t.iterator();
        //用于定位的索引
        int count = 0;
        while (iterator.hasNext()) {

            Object obj = iterator.next();

            //判断是否需要增加‘,’
            if (count > 0) {
                tempBuffer.append(',');
            }

            //根据不同的类型进行拼接字符串
            if (obj instanceof String) {
                try {
                    tempBuffer.append('\'').append(URLEncoder.encode(obj.toString(), "UTF-8")).append('\'');
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else if (obj instanceof Number) {
                tempBuffer.append(obj);
            }

            //索引+1
            count++;

        }
        //拼接结束符
        tempBuffer.append(')');

        //返回字符串
        return tempBuffer.toString();
    }
}
posted @ 2016-11-18 10:13  吴昭  阅读(233)  评论(0编辑  收藏  举报