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

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

Introduction

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

Prototype

public QueryRunner() 

Source Link

Document

Constructor for QueryRunner.

Usage

From source file:ch.vorburger.mariadb4j.MariaDB4jSampleTutorialTest.java

@Test
public void testEmbeddedMariaDB4j() throws Exception {
    DB db = DB.newEmbeddedDB(3308);//from   w  ww  .j a  va2  s  .  c om
    db.start();

    Connection conn = null;
    try {
        conn = db.getConnection();
        QueryRunner qr = new QueryRunner();

        // Should be able to create a new table
        qr.update(conn, "CREATE TABLE hello(world VARCHAR(100))");

        // Should be able to insert into a table
        qr.update(conn, "INSERT INTO hello VALUES ('Hello, world')");

        // Should be able to select from a table
        List<String> results = qr.query(conn, "SELECT * FROM hello", new ColumnListHandler<String>());
        Assert.assertEquals(1, results.size());
        Assert.assertEquals("Hello, world", results.get(0));

        // Should be able to source a SQL file
        db.source("ch/vorburger/mariadb4j/testSourceFile.sql");
        results = qr.query(conn, "SELECT * FROM hello", new ColumnListHandler<String>());
        Assert.assertEquals(3, results.size());
        Assert.assertEquals("Hello, world", results.get(0));
        Assert.assertEquals("Bonjour, monde", results.get(1));
        Assert.assertEquals("Hola, mundo", results.get(2));
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

From source file:de.unibremen.informatik.tdki.combo.data.JdbcTemplate.java

public JdbcTemplate(String url, String user, String password) {
    assert DbUtils.loadDriver("com.ibm.db2.jcc.DB2Driver");
    try {/*from   ww  w.j  a v  a2s. c o m*/
        connection = DriverManager.getConnection(url, user, password);
        qRunner = new QueryRunner();
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.ouc.cpss.dao.BaseDao.java

/**
 * sql?,?,,//from  www  .j a va  2s. c  o m
 *
 * @param sql
 * @return
 */
public boolean update(String sql, Object[] params) {
    Connection conn = null;
    boolean flag = false;
    try {
        conn = getConnection();
        QueryRunner qRunner = new QueryRunner();
        int i = qRunner.update(conn, sql, params);
        if (i > 0) {
            flag = true;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtils.closeQuietly(conn);
    }
    return flag;
}

From source file:cn.itcast.bbs.dao.TypeDao.java

public void deleteTypeById(int typeId) throws SQLException {
    QueryRunner runner = new QueryRunner();
    String sql = "delete from type where id = ?;";
    runner.update(JdbcUtil.getConnection(), sql, typeId);
}

From source file:com.pinterest.deployservice.db.DBUtilDAOImpl.java

@Override
public Connection getLock(String id) {
    Connection connection = null;
    try {//from  ww  w  .ja  va  2s .c  om
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);
        long status = new QueryRunner().query(connection, String.format(GET_LOCK_TEMPLATE, id, LOCK_TIMEOUT),
                SingleResultSetHandlerFactory.<Long>newObjectHandler());
        if (status == 1L) {
            return connection;
        }
    } catch (Exception e) {
        LOG.error("Failed to call getLock on id {}.", id, e);
    }
    DbUtils.closeQuietly(connection);
    return null;
}

From source file:com.odap.server.audit.ConfigHandler.java

public ConfigMessage registerNewServer(ConfigMessage config) throws TException {
    logger.info("Enter registerNewServer()");
    ConfigMessage msg = new ConfigMessage();

    QueryRunner qRunner = new QueryRunner();

    Integer account_id = null;/*from w  ww.j  a  v  a2s.  co  m*/
    Integer server_id = null;
    //Authenticate the user and get the account_id;
    String query = "SELECT * FROM joomla.cloud_users WHERE username = ? AND password = ?";
    {
        String parameters[] = { config.getUsername().replaceAll("[^A-Za-z0-9 ]", ""),
                DigestUtils.md5Hex(config.getPassword().replaceAll("[^A-Za-z0-9 ]", "")) };
        try {
            List<Map<String, Object>> mapList = (List<Map<String, Object>>) qRunner
                    .query(AuditServer.connectionPool.getConnection(), query, new MapListHandler(), parameters);

            if (mapList.size() < 1) {
                logger.warn("Username " + config.getUsername() + " not authenticated");
                return msg;
            }

            account_id = (Integer) mapList.get(0).get("account_id");

        } catch (SQLException e) {
            logger.error("Issue finding user account", e);
            return msg;
        }
    }

    String session_id = nextSessionId();
    {
        try {
            {
                query = "INSERT INTO servers (account_id,server_name,server_software,server_port,server_authentication_token,server_timezone,strip_predicates) VALUES (?,?,?,?,?,?,?)";
                Object parameters[] = { account_id.toString(),
                        config.getServer_name().replaceAll("[^A-Za-z0-9 ]", ""), config.getServer_software(),
                        new Short(config.getPort()), session_id, new Double(config.getTimezone_offset()),
                        config.strip_predicates };
                qRunner.update(AuditServer.connectionPool.getConnection(), query, parameters);
            }
            {
                String parameters[] = { account_id.toString(), config.getServer_name(), session_id };
                query = "SELECT * FROM servers WHERE account_id = ? AND server_name = ? and server_authentication_token = ?";
                List<Map<String, Object>> mapList = (List<Map<String, Object>>) qRunner.query(
                        AuditServer.connectionPool.getConnection(), query, new MapListHandler(), parameters);

                if (mapList.size() < 1) {
                    logger.error("Unable to find server after after registering it");
                    return msg;
                }

                server_id = (Integer) mapList.get(0).get("id");
            }
        } catch (SQLException e) {
            logger.error("Issue registering server", e);
        }
    }

    msg.token = session_id;
    msg.server_id = server_id.shortValue();
    msg.server = "dbauditcloud.com";
    logger.info("Exiting registerNewServer()");
    return msg;
}

From source file:cn.itcast.bbs.dao.ReplyDao.java

public void deleteReplyByTopicId(int topicId) throws SQLException {
    QueryRunner runner = new QueryRunner();
    String sql = "delete from reply where topic_id = ?;";
    runner.update(JdbcUtil.getConnection(), sql, topicId);
}

From source file:com.gs.obevo.dbmetadata.impl.dialects.HsqlMetadataDialect.java

@Override
public ImmutableCollection<DaUserType> searchUserTypes(final DaSchema schema, Connection conn)
        throws SQLException {
    QueryRunner query = new QueryRunner();

    ImmutableList<Map<String, Object>> maps = ListAdapter.adapt(query.query(conn,
            "select dom.DOMAIN_NAME AS USER_TYPE_NAME\n" + "from INFORMATION_SCHEMA.DOMAINS dom\n"
                    + "WHERE dom.DOMAIN_SCHEMA = ucase('" + schema.getName() + "')\n",
            new MapListHandler())).toImmutable();

    return maps.collect(new Function<Map<String, Object>, DaUserType>() {
        @Override// ww w  . j  a  v  a2s . c  o  m
        public DaUserType valueOf(Map<String, Object> map) {
            return new DaUserTypeImpl((String) map.get("USER_TYPE_NAME"), schema);
        }
    });
}

From source file:it.attocchi.db.DbUtilsConnector.java

public <T> T executeTop1(boolean keepConnOpen, String aTop1Query, Class<T> clazz) throws Exception {
    T result = null;//from   ww  w  . j  a  va  2  s .  c o  m

    // No DataSource so we must handle Connections manually
    QueryRunner run = new QueryRunner();

    try {

        /*
         * Sembra che il like con i parametri ufficiali non funzioni, forse
         * dovuto al fatto che son tutti object
         */
        logger.debug("Esecuzione di : " + aTop1Query);
        List<T> listTop1 = run.query(getConnection(), aTop1Query, getResultSetHandler(clazz));

        if (listTop1.size() > 0) {
            logger.debug(String.format("Record Trovati: %s", listTop1.size()));
            result = listTop1.get(0);
        }

    } finally {
        // Use this helper method so we don't have to check for null
        if (!keepConnOpen)
            close();
    }

    return result;
}

From source file:de.unibremen.informatik.tdki.combo.rewriting.FilterRewriterDB2.java

public FilterRewriterDB2(String project, Connection connection) {
    this.connection = connection;
    qRunner = new QueryRunner();
    // TODO: remove this at some point
    //initParameters();
    this.project = project;
}