Example usage for org.apache.commons.dbutils QueryRunner query

List of usage examples for org.apache.commons.dbutils QueryRunner query

Introduction

In this page you can find the example usage for org.apache.commons.dbutils QueryRunner query.

Prototype

public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException 

Source Link

Document

Executes the given SELECT SQL query and returns a result object.

Usage

From source file:org.rti.zcore.dar.utils.DatabaseUtils.java

/**
 * Fetch a single value; Support for adding value array
 * unused//  www  . j  a v  a  2s .  com
 *
 * @param sql
 * @param values
 * @return
 * @throws ServletException
 * @throws SQLException
 */
public static Object getScalar(String sql, ArrayList values) throws ServletException, SQLException {
    ResultSetHandler h = new ScalarHandler();
    DataSource dataSource = null;
    dataSource = DatabaseUtils.getZEPRSDataSource();
    QueryRunner run = new QueryRunner(dataSource);
    Object result = run.query(sql, values.toArray(), h);
    return result;
}

From source file:org.rti.zcore.dar.utils.DatabaseUtils.java

/**
 * Return the first resultset row stuffed into a bean
 *
 * @param clazz/*from  w w w.  j  a  va  2s  . co m*/
 * @param sql
 * @param values
 * @return
 * @throws ServletException
 * @throws SQLException
 */
public static Object getBean(Class clazz, String sql, ArrayList values)
        throws ServletException, SQLException, ObjectNotFoundException {
    // DataSource dataSource = null;
    //dataSource = DatabaseUtils.getZEPRSDataSource();
    QueryRunner run = new QueryRunner(getZEPRSDataSource());
    ResultSetHandler h = new BeanHandler(clazz);
    // return the results in a new object generated by the BeanHandler.
    Object result = null;
    //  try {
    try {
        result = run.query(sql, values.toArray(), h);
    } catch (SQLException e) {
        log.error("SQL - params: " + values + "Error: " + e);
    }
    // log.info("Getting the bean " + clazz.toString());
    /* } catch (SQLException e) {
    log.error("SQL - params: " + values + "Error: " + e);
    }*/
    if (result == null) {
        throw new ObjectNotFoundException();
    }

    return result;
}

From source file:org.rti.zcore.dar.utils.DatabaseUtils.java

/**
 * Fetch a simple list of values//from w w  w.  j ava 2 s  .  c  om
 *
 * @param clazz
 * @param sql
 * @param values
 * @return
 * @throws ServletException
 * @throws SQLException
 */
public static List getList(Class clazz, String sql, ArrayList values) throws ServletException, SQLException {
    DataSource dataSource = null;
    try {
        dataSource = DatabaseUtils.getZEPRSDataSource();
    } catch (ServletException e) {
        log.error(e);
    }
    QueryRunner run = null;
    try {
        run = new QueryRunner(dataSource);
    } catch (Exception e) {
        log.error(e);
    }
    // ResultSetHandler h = new BeanListHandler(clazz);
    ResultSetHandler h = new BeanListHandler(clazz, new BasicRowProcessor(new ZEPRSBeanProcessor()));
    // ResultSetHandler h = new BeanListHandler(clazz,new BasicRowProcessor(new BasicColumnProcessor()));
    // return the results in a new object generated by the BeanHandler.
    List list = null;
    try {
        list = (List) run.query(sql, values.toArray(), h);
    } catch (SQLException e) {
        log.error(e);
    }
    return list;
}

From source file:org.rti.zcore.dar.utils.DatabaseUtils.java

/**
 * For classes w/ nested objects such as AuditInfo
 *
 * @param clazz/*w  ww.  jav a2  s .c  o m*/
 * @param sql
 * @param values
 * @param convert
 * @return
 * @throws ServletException
 * @throws SQLException
 */
public static List getList(Class clazz, String sql, ArrayList values, RowProcessor convert)
        throws ServletException, SQLException {
    DataSource dataSource = null;
    dataSource = DatabaseUtils.getZEPRSDataSource();
    QueryRunner run = new QueryRunner(dataSource);
    ResultSetHandler h = new BeanListHandler(clazz, convert);
    // return the results in a new object generated by the BeanHandler.
    List list = (List) run.query(sql, values.toArray(), h);
    return list;

}

From source file:org.rti.zcore.dar.utils.DatabaseUtils.java

/**
 * puts results set in key value pair into Map
 * unused/*from  w ww.ja  va  2s  . c  om*/
 *
 * @param sql
 * @param values
 * @return
 * @throws ServletException
 * @throws SQLException
 */
public static Map getArrayList(String sql, ArrayList values) throws ServletException, SQLException {
    ResultSetHandler h = new ArrayListHandler();
    DataSource dataSource = null;
    dataSource = DatabaseUtils.getZEPRSDataSource();
    QueryRunner run = new QueryRunner(dataSource);
    List result = (List) run.query(sql, values.toArray(), h);
    Map map = new HashMap();
    for (int i = 0; i < result.size(); i++) {
        Object[] keyVal = (Object[]) result.get(i);
        map.put(keyVal[1], keyVal[0]);

    }
    return map;
}

From source file:org.sonar.server.db.migrations.v36.ViolationConverter.java

private void convert(List<Map<String, Object>> rows, Long[] violationIds) throws SQLException {
    Connection readConnection = null;
    Connection writeConnection = null;
    try {/*from   w w  w.j a  v a  2 s  .c o  m*/
        readConnection = db.getDataSource().getConnection();
        writeConnection = db.getDataSource().getConnection();
        writeConnection.setAutoCommit(false);

        List<Object[]> allParams = Lists.newArrayList();
        List<Map<String, Object>> allComments = Lists.newArrayList();

        QueryRunner runner = new QueryRunner();
        for (Map<String, Object> row : rows) {
            Long componentId = (Long) row.get(PROJECT_ID);
            if (componentId == null) {
                continue;
            }
            String issueKey = UUID.randomUUID().toString();
            String status, severity, reporter = null;
            boolean manualSeverity;
            Object createdAt = Objects.firstNonNull(row.get(CREATED_AT), ONE_YEAR_AGO);
            Object updatedAt;
            Long reviewId = (Long) row.get(REVIEW_ID);
            if (reviewId == null) {
                // violation without review
                status = STATUS_OPEN;
                manualSeverity = false;
                severity = (String) row.get(SEVERITY);
                updatedAt = createdAt;
            } else {
                // violation + review
                String reviewStatus = (String) row.get(REVIEW_STATUS);
                status = (STATUS_OPEN.equals(reviewStatus) ? STATUS_CONFIRMED : reviewStatus);
                manualSeverity = Objects.firstNonNull((Boolean) row.get(REVIEW_MANUAL_SEVERITY), false);
                severity = (String) row.get(REVIEW_SEVERITY);
                updatedAt = Objects.firstNonNull(row.get(REVIEW_UPDATED_AT), ONE_YEAR_AGO);
                if ((Boolean) row.get(REVIEW_MANUAL_VIOLATION)) {
                    reporter = referentials.userLogin((Long) row.get(REVIEW_REPORTER_ID));
                }

                List<Map<String, Object>> comments = runner.query(readConnection,
                        ReviewCommentsHandler.SQL + reviewId, new ReviewCommentsHandler());
                for (Map<String, Object> comment : comments) {
                    comment.put(ISSUE_KEY, issueKey);
                    allComments.add(comment);
                }
            }
            Object[] params = new Object[20];
            params[0] = issueKey;
            params[1] = componentId;
            params[2] = row.get(ROOT_PROJECT_ID);
            params[3] = row.get(RULE_ID);
            params[4] = severity;
            params[5] = manualSeverity;
            params[6] = row.get(MESSAGE);
            params[7] = row.get(LINE);
            params[8] = row.get(COST);
            params[9] = status;
            params[10] = row.get(REVIEW_RESOLUTION);
            params[11] = row.get(CHECKSUM);
            params[12] = reporter;
            params[13] = referentials.userLogin((Long) row.get(REVIEW_ASSIGNEE_ID));
            params[14] = referentials.actionPlan((Long) row.get(PLAN_ID));
            params[15] = row.get(REVIEW_DATA);
            params[16] = createdAt;
            params[17] = updatedAt;
            params[18] = createdAt;
            params[19] = updatedAt;
            allParams.add(params);
        }
        runner.batch(writeConnection, SQL_INSERT_ISSUE, allParams.toArray(new Object[allParams.size()][]));
        insertComments(writeConnection, allComments);
        runner.update(writeConnection, SQL_DELETE_RULE_FAILURES, violationIds);
        writeConnection.commit();
        progress.increment(rows.size());

    } finally {
        DbUtils.closeQuietly(readConnection);
        DbUtils.closeQuietly(writeConnection);
    }
}

From source file:org.teiid.embedded.helper.utils.JDBCUtils.java

public static void query(Connection conn, String sql) throws SQLException {

    System.out.println("Query SQL: " + sql);
    QueryRunner runner = new QueryRunner();
    ArrayListHandler handler = new ArrayListHandler();
    List<Object[]> results = runner.query(conn, sql, handler);
    dumpResults(results);/* w  ww  .j a v  a 2  s  .  c o m*/
}

From source file:pe.gob.sunat.tecnologia3.arquitectura.framework.desktop.dominio.dao.sqlite.BaseDaoSqlite.java

@Override
public List<T> obtenerRegistros() {
    List<T> object = null;/*from w  w  w  .  java2 s .  c o m*/
    logger.log(Level.INFO, "metodo: obtenerRegistros...");
    try {
        StringBuffer sqlQuery = new StringBuffer();
        sqlQuery.append("select * from ");
        sqlQuery.append(nombreTabla);
        sqlQuery.append(" where status=1 ");

        QueryRunner queryRunner = new QueryRunner();
        ResultSetHandler blh = new BeanListHandler(entidad);

        object = (List<T>) queryRunner.query(getConexion(), sqlQuery.toString(), blh);

        logger.log(Level.INFO, "Ejecutor el query.");
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Error en el query.{0}", ex.getMessage());
    }
    return object;
}

From source file:reasoning.TestUtils.java

public static <E> Multiset<Tuple<E>> getTuples(Connection connection, String query) {
    final Multiset<Tuple<E>> result = HashMultiset.create();
    QueryRunner qRunner = new QueryRunner();
    try {/*from  w  w w  . j a  v a 2s.c o  m*/
        qRunner.query(connection, query, new ResultSetHandler() {

            @Override
            public Object handle(ResultSet rs) throws SQLException {
                int columns = rs.getMetaData().getColumnCount();
                while (rs.next()) {
                    Tuple<E> t = new Tuple<E>();
                    for (int i = 1; i <= columns; i++) {
                        t.add((E) rs.getObject(i));
                    }
                    result.add(t);
                }
                return null;
            }
        });
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
    return result;
}

From source file:ttf.persistence.sql.TopicListRSH.java

@Override
public Collection<Topic> handle(ResultSet rs) throws SQLException {
    QueryRunner run = new QueryRunner(dataSource);

    List<Topic> topics = new LinkedList<Topic>();

    while (rs.next()) {
        Topic topic = topicFactory.build(rs.getString(1));
        topic.setTitle(rs.getString(2));

        // load features
        String sql = "SELECT type, name, score FROM TopicFeatures WHERE topicId = ?";
        ArrayListHandler h = new ArrayListHandler();
        List<Object[]> features = run.query(sql, h, topic.getId());

        // parse features
        for (Object[] o : features) {
            String type = (String) o[0];
            String name = (String) o[1];
            Double score = (Double) o[2];
            if (type.equals("entity")) {
                topic.getEntityGroup().put(name, new NumericalValue(score));
            } else if (type.equals("term")) {
                topic.getTermGroup().put(name, new NumericalValue(score));
            }// w w w. j  a v a 2  s .c  o  m
        }

        topics.add(topic);
    }

    return topics;
}