Example usage for java.sql Statement execute

List of usage examples for java.sql Statement execute

Introduction

In this page you can find the example usage for java.sql Statement execute.

Prototype

boolean execute(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which may return multiple results.

Usage

From source file:com.sqewd.open.dal.core.persistence.db.H2DbPersister.java

private void createIndex(Element parent, Class<?> cls, SimpleDbQuery dbq, Statement stmnt) throws Exception {
    NodeList nl = XMLUtils.search(_CONFIG_SETUP_INDEXES_, parent);
    if (nl != null && nl.getLength() > 0) {
        for (int ii = 0; ii < nl.getLength(); ii++) {
            Element elm = (Element) nl.item(ii);

            String iname = elm.getAttribute("name");
            if (iname == null || iname.isEmpty())
                throw new Exception("Invalid Configuration : Missing or empty attribute [name]");
            String icolumns = elm.getAttribute("columns");
            if (icolumns == null || icolumns.isEmpty())
                throw new Exception("Invalid Configuration : Missing or empty attribute [columns]");
            List<KeyValuePair<String>> columns = new ArrayList<KeyValuePair<String>>();
            KeyValuePair<String> cp = new KeyValuePair<String>();
            cp.setKey(iname);/*from   www .j ava 2s . c  o m*/
            cp.setValue(icolumns);
            columns.add(cp);

            List<String> createsql = dbq.getCreateIndexDDL(cls, columns);
            for (String sql : createsql) {
                log.debug("INDEX SQL [" + sql + "]");
                stmnt.execute(sql);
            }
        }
    }
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testTransaction()
        throws SQLException, IOException, ZooKeeperConnectionException, InterruptedException {
    stat.execute(DruidParserTestUtil.SEED[0]);
    TEST_UTIL.waitTableAvailable(Bytes.toBytes("User"));
    stat.execute(DruidParserTestUtil.SEED[1]);
    TEST_UTIL.waitTableAvailable(Bytes.toBytes("Photo"));

    conn.setAutoCommit(false);/*  ww w .ja v  a 2  s  .c o  m*/
    Statement stat = conn.createStatement();
    stat.addBatch("Insert into User(user_id,name) values(1,'testTransaction');");
    stat.addBatch("Insert into Photo(user_id,photo_id,tag) values(1,1,'tag');");
    int[] ret = stat.executeBatch();
    conn.commit();
    int successNum = 0;
    for (int i : ret) {
        if (i == 1)
            successNum++;
    }
    assertTrue(successNum == 2);

    ResultSet rs = stat.executeQuery("SELECT * FROM User WHERE user_id=1");
    assertTrue(rs.next());
    assertTrue(rs.getString("name").equals("testTransaction"));

    rs = stat.executeQuery("SELECT * FROM Photo WHERE user_id=1 and photo_id=1");
    assertTrue(rs.next());
    assertTrue(rs.getString("tag").equals("tag"));

}

From source file:com.xpn.xwiki.store.XWikiHibernateBaseStore.java

/**
 * Execute an SQL statement using Hibernate.
 *
 * @param sql the SQL statement to execute
 * @param session the Hibernate Session in which to execute the statement
 *//*from ww  w. j  a v  a2s.  co  m*/
private void executeSQL(final String sql, Session session) {
    session.doWork(new Work() {
        public void execute(Connection connection) throws SQLException {
            Statement stmt = null;
            try {
                stmt = connection.createStatement();
                stmt.execute(sql);
            } finally {
                try {
                    if (stmt != null) {
                        stmt.close();
                    }
                } catch (Exception e) {
                }
            }
        }
    });
}

From source file:hmp.HMPReadFilterer.java

private void createSampleForRunInDatabase(Statement s, String runDate, String tag, String sample, int region,
        PrintWriter debug) throws SQLException {
    System.out.println(sample + " not found, creating ");
    ResultSet rs = s.executeQuery("select run_id from run where date='" + runDate + "'");
    int runID = -1;
    int barcodeID = -1;
    while (rs.next()) {
        runID = rs.getInt("run_id");
    }// w  w w. j a va  2s. c om
    rs = s.executeQuery("select barcode_id from barcodes where barcode_sequence=\"" + tag + "\"");
    while (rs.next()) {
        barcodeID = rs.getInt("barcode_id");
    }
    String sql = "insert into sample (run_id, sample_name, sample_barcode_id, plate_region, sample_description) values ("
            + runID + ",\"" + sample + "\"," + barcodeID + "," + region + "," + "\"test\")";
    debug.println(sql);
    debug.flush();
    try {
        System.out.println(sql);
        s.execute(sql);
    } catch (SQLException e) {
        System.out.println("barcode=" + tag);
        System.out.println(sql);
        e.printStackTrace();
    }
}

From source file:gobblin.source.extractor.extract.jdbc.JdbcExtractor.java

/**
 * Execute query using JDBC simple Statement Set fetch size
 *
 * @param cmds commands - query, fetch size
 * @return JDBC ResultSet//from  w  w w. j  a v a2s  . co  m
 * @throws Exception
 */
private CommandOutput<?, ?> executeSql(List<Command> cmds) {
    String query = null;
    int fetchSize = 0;

    for (Command cmd : cmds) {
        if (cmd instanceof JdbcCommand) {
            JdbcCommandType type = (JdbcCommandType) cmd.getCommandType();
            switch (type) {
            case QUERY:
                query = cmd.getParams().get(0);
                break;
            case FETCHSIZE:
                fetchSize = Integer.parseInt(cmd.getParams().get(0));
                break;
            default:
                this.log.error("Command " + type.toString() + " not recognized");
                break;
            }
        }
    }

    this.log.info("Executing query:" + query);
    ResultSet resultSet = null;
    try {
        this.jdbcSource = createJdbcSource();
        this.dataConnection = this.jdbcSource.getConnection();
        Statement statement = this.dataConnection.createStatement();

        if (fetchSize != 0 && this.getExpectedRecordCount() > 2000) {
            statement.setFetchSize(fetchSize);
        }
        final boolean status = statement.execute(query);
        if (status == false) {
            this.log.error("Failed to execute sql:" + query);
        }
        resultSet = statement.getResultSet();
    } catch (Exception e) {
        this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e);
    }

    CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput();
    output.put((JdbcCommand) cmds.get(0), resultSet);
    return output;
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

/**
 * {@inheritDoc}/*from   ww  w .  j  a v  a2s .c  o m*/
 */
@Override
protected void wipeTree(FxTreeMode mode, Statement stmt, FxPK rootPK) throws SQLException {
    DBStorage storage = StorageManager.getStorageImpl();
    stmt.execute(storage.getReferentialIntegrityChecksStatement(false));
    try {
        stmt.executeUpdate("DELETE FROM " + getTable(mode));
        stmt.executeUpdate("INSERT INTO " + getTable(mode)
                + " (ID,NAME,MODIFIED_AT,DIRTY,PARENT,DEPTH,CHILDCOUNT,REF,TEMPLATE,LFT,RGT) " + "VALUES ("
                + ROOT_NODE + ",'Root'," + storage.getTimestampFunction() + ","
                + storage.getBooleanFalseExpression() + ",NULL,1,0," + rootPK.getId() + ",NULL,1," + MAX_RIGHT
                + ")");
    } finally {
        stmt.executeUpdate(storage.getReferentialIntegrityChecksStatement(true));
    }
}

From source file:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java

/**
 * ???????/*from   w w w. j a  v  a 2s .co m*/
 * 
 * @param user
 * @param password
 * @param adminUser
 * @param adminPassword
 * @param schema
 * @param objectTypeList
 * @throws MojoExecutionException
 */
private void dropObjectSpecifiedTypes(String schema, String adminUser, String adminPassword,
        List<String> objectTypeList) throws MojoExecutionException {

    PreparedStatement stmtMeta = null;
    Statement stmt = null;

    Connection conn = null;
    try {
        conn = DriverManager.getConnection(url, adminUser, adminPassword);

        String dropObjectTypes = "'" + org.apache.commons.lang.StringUtils.join(objectTypeList, "','") + "'";

        stmtMeta = conn
                .prepareStatement("SELECT object_type, object_name FROM dba_objects WHERE object_type in ("
                        + dropObjectTypes + ") and owner = ?");
        stmtMeta.setString(1, schema);

        ResultSet rsMeta = stmtMeta.executeQuery();
        while (rsMeta.next()) {
            String objectType = rsMeta.getString("OBJECT_TYPE");
            String objectName = rsMeta.getString("OBJECT_NAME");
            if (!objectName.startsWith("BIN$")) {
                dropObject(conn, objectType, schema + "." + objectName);
            }
        }
        stmt = conn.createStatement();
        stmt.execute("PURGE RECYCLEBIN");
    } catch (SQLException e) {
        throw new MojoExecutionException("Drop Object?", e);
    } finally {
        StatementUtil.close(stmtMeta);
        StatementUtil.close(stmt);
        ConnectionUtil.close(conn);
    }
}

From source file:fi.ni.IFC_ClassModel.java

public void listRDF(OutputStream outputStream, String path, VirtConfig virt) throws IOException, SQLException {

    BufferedWriter out = null;//w  ww. jav  a 2 s .  c  o  m
    Connection c = null;
    String prefix_query = "PREFIX : <" + path + "> " + "PREFIX instances: <http://drum.cs.hut.fi/instances#> "
            + "PREFIX owl: <" + Namespace.OWL + "> " + "PREFIX ifc: <" + Namespace.IFC + "> " + "PREFIX xsd: <"
            + Namespace.XSD + "> " + "INSERT IN GRAPH <" + path + "> { ";

    try {
        //Setup file output
        out = new BufferedWriter(new OutputStreamWriter(outputStream));
        out.write("@prefix : <" + path + ">.\n");
        out.write("@prefix instances: <http://drum.cs.hut.fi/instances#>. \n");
        out.write("@prefix owl: <" + Namespace.OWL + "> .\n");
        out.write("@prefix ifc: <" + Namespace.IFC + "> .\n");
        out.write("@prefix xsd: <" + Namespace.XSD + "> .\n");
        out.write("\n");

        //If necessary, setup virtuoso connection
        if (virt != null) {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setUsername(virt.user);
            dataSource.setPassword(virt.password);
            dataSource.setUrl(virt.jdbc_uri);
            dataSource.setMaxActive(100);
            dataSource.setDriverClassName("virtuoso.jdbc4.Driver");
            c = dataSource.getConnection();
        }

        for (Map.Entry<Long, Thing> entry : object_buffer.entrySet()) {
            Thing gobject = entry.getValue();
            String triples = generateTriples(gobject);
            out.write(triples);

            if (virt != null) {
                Statement stmt = c.createStatement();
                StringBuilder queryString = new StringBuilder();
                queryString.append(prefix_query);
                queryString.append(triples);
                queryString.append("}");
                boolean more = stmt.execute("sparql " + queryString.toString());
                if (!more) {
                    System.err.println("INSERT failed.");
                }
                if (stmt != null)
                    stmt.close();
            }
        }

    } finally {
        if (out != null)
            out.close();
        if (c != null)
            c.close();
    }
}

From source file:com.adaptris.jdbc.connection.FailoverConnection.java

private void testConnection() throws SQLException {
    Statement stmt = sqlConnection.createStatement();
    ResultSet rs = null;/*from   w ww  .j  a va  2  s. c  om*/
    try {
        if (isEmpty(config.getTestStatement())) {
            return;
        }
        if (config.getAlwaysValidateConnection()) {
            if (isDebugMode()) {
                rs = stmt.executeQuery(config.getTestStatement());
                if (rs.next()) {
                    StringBuffer sb = new StringBuffer("TestStatement Results - ");
                    ResultSetMetaData rsm = rs.getMetaData();
                    for (int i = 1; i <= rsm.getColumnCount(); i++) {
                        sb.append("[");
                        sb.append(rsm.getColumnName(i));
                        sb.append("=");
                        try {
                            sb.append(rs.getString(i));
                        } catch (Exception e) {
                            sb.append("'unknown'");
                        }
                        sb.append("] ");
                    }
                    logR.trace(sb.toString());
                }
            } else {
                stmt.execute(config.getTestStatement());
            }
        }
    } finally {
        JdbcUtil.closeQuietly(rs);
        JdbcUtil.closeQuietly(stmt);
    }
}

From source file:com.edgenius.wiki.installation.UpgradeServiceImpl.java

@SuppressWarnings("unused")
private void up3000To3100() throws Exception {
    log.info("Version 3.0 to 3.1 is upgarding");

    String root = DataRoot.getDataRoot();
    if (FileUtil.exist(root + Server.FILE)) {
        Server server = new Server();
        Properties prop = FileUtil.loadProperties(root + Server.FILE);
        server.syncFrom(prop);/* w w w . j  av  a  2  s .  c  o  m*/
        if (server.getMqServerEmbedded() == null || BooleanUtils.toBoolean(server.getMqServerEmbedded())) {
            //embedded
            if (!server.getMqServerUrl().startsWith("tcp://")) {
                server.setMqServerUrl(
                        "tcp://" + server.getMqServerUrl() + "?wireFormat.maxInactivityDuration=0");
                server.syncTo(prop);
                prop.store(FileUtil.getFileOutputStream(root + Server.FILE), "save by system program");
            }
        }
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // database - remove all quartz tables - we don't backup Exportable job(backup and remove space) - it is not perfect but not big issue.
    if (FileUtil.exist(root + Server.FILE)) {
        Server server = new Server();
        Properties prop = FileUtil.loadProperties(root + Server.FILE);
        server.syncFrom(prop);
        String dbType = server.getDbType();

        String migrateSQL = dbType + "-3000-3100.sql";
        DBLoader loader = new DBLoader();
        ConnectionProxy con = loader.getConnection(dbType, server.getDbUrl(), server.getDbSchema(),
                server.getDbUsername(), server.getDbPassword());
        loader.runSQLFile(dbType, migrateSQL, con);

        //reload quartz table
        log.info("Initialize quartz tables for system...");
        Statement stat = con.createStatement();
        Statement dropStat = con.createStatement();
        List<String> lines = loader.loadSQLFile(dbType, dbType + "-quartz.sql");
        for (String sql : lines) {
            sql = sql.replaceAll("\n", " ").trim();
            if (sql.toLowerCase().startsWith("drop ")) {
                try {
                    dropStat.execute(sql);
                } catch (Exception e) {
                    log.error("Drop operation failed...." + sql);
                }
                continue;
            }
            stat.addBatch(sql);
        }
        stat.executeBatch();

        dropStat.close();
        stat.close();
        con.close();
    }

}