Java SQL Query queryForList(Connection conn, String sql, int limit)

Here you can find the source of queryForList(Connection conn, String sql, int limit)

Description

query For List

License

Apache License

Declaration

public static List<Map> queryForList(Connection conn, String sql,
            int limit) throws SQLException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static List<Map> queryForList(Connection conn, String sql,
            int limit) throws SQLException {
        PreparedStatement ps = conn.prepareStatement(sql.trim());
        ps.setMaxRows(limit);//from w w w  .  j av  a2  s .c  o  m
        ps.setFetchDirection(ResultSet.FETCH_FORWARD);
        ResultSet rs = ps.executeQuery();
        return toListMap(limit, rs);
    }

    public static List<Map> toListMap(int limit, ResultSet rs)
            throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int count = 0;
        List<Map> list = new ArrayList<Map>();
        while (rs.next()) {
            Map row = new HashMap();
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                row.put(rsmd.getColumnName(i), rs.getObject(i));
            }
            list.add(row);
            count++;
            if (count >= limit) {
                break;
            }
        }
        return list;
    }
}

Related

  1. getSqlQuery(Statement statement, Object[] args)
  2. getStatement(Connection con, String query, Object... bits)
  3. query(Connection conn, String sql)
  4. query(Connection conn, String sql, Object[] params, Class beanClass)
  5. query(Connection connection, String sql, boolean isClose, Object... params)
  6. queryObjectList(Connection con, String sql, Class objClass)
  7. queryProjectTicketIdFromTicketId(Connection db, int ticketId)
  8. queryReturnRS(String sql)
  9. runQuery(Connection con, String query)