java 資料庫查詢工具類.

來源:互聯網
上載者:User

標籤:java 資料庫查詢工具類.



import java.util.List;
import java.util.Map;

/**
 * 資料庫查詢工具類.
 *
 */
public class QueryTool {
    
    /**
     * Checks if is condition.
     *
     * @param obj the obj
     * @return true, if is condition
     */
    public static boolean isCondition(Object obj) {
        if ("".equals(getString(obj)))
            return false;
        else
            return true;
    }

    /**
     * Gets the string from Object,null值轉換為空白字串.
     *
     * @param obj the obj
     * @return the string
     */
    public static String getString(Object obj) {
        return obj != null ? obj.toString() : "";
    }

    /**
     * 拼接sql in條件.
     *
     * @param columnKey the column key
     * @param columnValueList the column value list
     * @param joinOp the join op
     * @param sb the sb
     */
    public static void appendConditionIn(String columnKey, List<String> columnValueList,
            String joinOp, StringBuffer sb) {
        if (QueryTool.isCondition(columnValueList)) {
            sb.append(" " + joinOp + " " + columnKey + " in " + QueryTool.listToSqlIn(columnValueList));
        }
    }
    
    /**
     * 拼接sql 條件.
     *
     * @param columnKey the column key
     * @param columnValue the column value
     * @param joinOp the join op
     * @param op the op
     * @param sb the sb
     * @param paramsList the params list
     */
    public static void appendCondition(String columnKey, Object columnValue,
            String joinOp, String op, StringBuffer sb, List<Object> paramsList) {
        if (QueryTool.isCondition(columnValue)) {
            sb.append(" " + joinOp + " " + columnKey + " " + op + " ?");
            paramsList.add(columnValue);
        }
    }

    /**
     * 生產分頁sql.
     *
     * @param sql the sql
     * @param pageIndex the page index
     * @param pageSize the page size
     * @param paramsList the params list
     * @return the string
     */
    public static String buildPageSql(String sql, int pageIndex, long pageSize,
            List<Object> paramsList) {
        long fromRowNum = pageSize * (pageIndex - 1) + 1;
        long toRowNum = pageSize * pageIndex;
        StringBuffer sbNewSql = new StringBuffer();

        sbNewSql.append("select x.*");
        sbNewSql.append(" from (select rownum x_rownum,o.* from (").append(sql)
                .append(") o) x");
        sbNewSql.append(" where x_rownum>= ?").append(" and x_rownum<= ?");
        sbNewSql.append(" order by x.x_rownum");
        paramsList.add(fromRowNum);
        paramsList.add(toRowNum);

        return sbNewSql.toString();
    }

    /**
     * 產生統計sql.
     *
     * @param sql the sql
     * @return the string
     */
    public static String buildCountSql(String sql) {
        return "select count(*) from (" + sql + ")";
    }

    /**
     * 取得map中對應資料,為null或空時轉換為預設值.
     *
     * @param map the map
     * @param name the name
     * @param replace the replace
     * @return the property
     */
    public static String getProperty(Map<String, ?> map, String name,
            String replace) {
        return map.get(name) != null
                && map.get(name).toString().trim().length() > 0 ? map.get(name)
                .toString() : replace;
    }

    /**
     * List to sql in.
     *
     * @param stringList the string list
     * @return the string
     */
    public static String listToSqlIn(List<String> stringList) {
        StringBuilder sb = new StringBuilder();

        if (stringList == null || stringList.size() == 0)
            return "";

        for (String string : stringList) {

            if (sb.length() == 0)
                sb.append(" (‘").append(string).append("‘");
            else
                sb.append(",‘").append(string).append("‘");
        }

        sb.append(") ");
        
        return sb.toString();
    }
    
    /**
     * 根據***取得性別.
     *
     * @param val the val
     * @return the sex from id
     */
    public static boolean getSexFromID(String val) {
        boolean sex = false;
        // 15位***號碼
        if (15 == val.length()) {
          if (Integer.valueOf(val.charAt(14) / 2) * 2 != val.charAt(14))
            sex = true;
          else
            sex = false;
        }
        // 18位***號碼
        if (18 == val.length()) {
          if (Integer.valueOf(val.charAt(16) / 2) * 2 != val.charAt(16))
            sex = true;
          else
            sex = false;
        }
        return sex;
      }
    
    /**
     * ***號15轉18位
     *
     * @author cjj 2010-5-13下午01:04:53
     * @param id
     * @return
     */
    public static final String getNewEighteenId(String id) {

        final int[] W = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2,
                1 };
        final String[] A = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3",
                "2" };
        int i, j, s = 0;
        String newid;
        newid = id;
        newid = newid.substring(0, 6) + "19" + newid.substring(6, id.length());
        for (i = 0; i < newid.length(); i++) {
            j = Integer.parseInt(newid.substring(i, i + 1)) * W[i];
            s = s + j;
        }
        s = s % 11;
        newid = newid + A[s];

        return newid;

    }

    /**
     * ***號18轉15位
     *
     * @author cjj 2010-5-13下午02:06:51
     * @param id
     * @return
     */
    public static String getNewFifteenId(String id) {
        String newid = id.substring(0, 6) + id.substring(8, id.length() - 1);
        return newid;
    }
    
    /**
     * ***號15,18位互換.
     *
     * @param id the id
     * @return the exchange p id
     */
    public static String getExchangePId(String id) {
        if (id.length()==15)
            return getNewEighteenId(id);
        else if (id.length()==18)
            return getNewFifteenId(id);
        else
            return id;        
    }

}




使用:

   
    public Page findLoginRecordList(String machineCode,String pageIndex,String pagesize){
        int pageIndexInt=Integer.valueOf(pageIndex);
        int pagesizeInt=Integer.valueOf(pagesize);
        List<Object> paramsList = new ArrayList<Object>(); //定義一個拼接參數的集合
        StringBuffer s = new StringBuffer();
        s.append("select t.certNo, t.CLIENT,t.TYPE, to_char(t.inouttime,‘mm/dd hh24:mi:ss‘) as INOUTTIME from DC_LOGINRECORD t where 1=1 ");
        QueryTool.appendCondition("t.machinecode",machineCode,"AND","=" ,s, paramsList);//拼接條件
        s.append("  order by t.inouttime desc");
        String sql = QueryTool.buildCountSql(s.toString()); //查詢總數的sql
        long totalSize = this.queryForInt(sql,paramsList.toArray(new Object[paramsList.size()])); //jdbc查詢
        if(totalSize > 0){
            String sl = QueryTool.buildPageSql(s.toString(), pageIndexInt,pagesizeInt , paramsList);//拼接分頁
            List<Map<String,Object>> list = this.queryForList(sl,paramsList.toArray(new Object[paramsList.size()])); //jdbc查詢
            int start = pagesizeInt *(pageIndexInt -1)+1; //本頁資料在資料庫中的起始位置
            return new Page(pagesizeInt *(start -1)+1, totalSize, pagesizeInt, list);
        }else{
            return new Page(0, 0, 10, new ArrayList());
        }
    }





備忘:

分頁的類:


import java.io.Serializable;
import java.util.ArrayList;

/**
 * 分頁對象. 包含資料及分頁資訊.
 */
public class Page implements Serializable {

    static private int DEFAULT_PAGE_SIZE = 20;

    /**
     * 每頁的記錄數
     */
    private int pageSize = DEFAULT_PAGE_SIZE;

    /**
     * 當前頁第一條資料在List中的位置,從0開始
     */
    private int start;

    /**
     * 當前頁中存放的記錄,類型一般為List
     */
    private Object data;

    /**
     * 總記錄數
     */
    private long totalCount;

    /**
     * 構造方法,只構造空頁
     */
    public Page() {
        this(0, 0, DEFAULT_PAGE_SIZE, new ArrayList());
    }

    /**
     * 預設構造方法
     *
     * @param start
     *            本頁資料在資料庫中的起始位置
     * @param totalSize
     *            資料庫中總記錄條數
     * @param pageSize
     *            本頁容量
     * @param data
     *            本頁包含的資料
     */
    public Page(int start, long totalSize, int pageSize, Object data) {
        this.pageSize = pageSize;
        this.start = start;
        this.totalCount = totalSize;
        this.data = data;
    }

    /**
     * 取資料庫中包含的總記錄數
     */
    public long getTotalCount() {
        return this.totalCount;
    }

    /**
     * 取總頁數
     */
    public long getTotalPageCount() {
        if (totalCount % pageSize == 0)
            return totalCount / pageSize;
        else
            return totalCount / pageSize + 1;
    }

    /**
     * 取每頁資料容量
     */
    public int getPageSize() {
        return pageSize;
    }

    /**
     * 當前頁中的記錄
     */
    public Object getResult() {
        return data;
    }

    /**
     * 取當前頁碼,頁碼從1開始
     */
    public int getCurrentPageNo() {
        return start / pageSize + 1;
    }

    /**
     * 是否有下一頁
     */
    public boolean hasNextPage() {
        return this.getCurrentPageNo() < this.getTotalPageCount() - 1;
    }

    /**
     * 是否有上一頁
     */
    public boolean hasPreviousPage() {
        return this.getCurrentPageNo() > 1;
    }

    /**
     * 擷取任一頁第一條資料的位置,每頁條數使用預設值
     */
    protected static int getStartOfPage(int pageNo) {
        return getStartOfPage(pageNo, DEFAULT_PAGE_SIZE);
    }

    /**
     * 擷取任一頁第一條資料的位置,startIndex從0開始
     */
    public static int getStartOfPage(int pageNo, int pageSize) {
        return (pageNo - 1) * pageSize;
    }
}

java 資料庫查詢工具類.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.