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.datatorrent.contrib.hive.HiveOperator.java

/**
 * Function to process each incoming tuple. The input is FilePartitionMapping
 * which is a POJO containing filename which is already committed and will not
 * be changed.The POJO also contains the hive partitions to which the
 * respective files will be moved./*from   w ww  .  ja va 2s  .  c  o  m*/
 *
 * @param tuple
 *          incoming tuple which has filename and hive partition.
 */
@Override
public void processTuple(FilePartitionMapping tuple) {
    String command = processHiveFile(tuple);
    logger.debug("commands is {}", command);
    if (command != null) {
        Statement stmt;
        try {
            stmt = store.getConnection().createStatement();
            stmt.execute(command);
        } catch (SQLException ex) {
            throw new RuntimeException("Moving file into hive failed" + ex);
        }
    }

}

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

private void loadProcedureFromFile(String file) {
    String path = "udf/" + file;
    StringBuilder builder = new StringBuilder();
    try {/*w ww  . j a  v  a2 s . c o  m*/
        BufferedReader input = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(path)));
        String line;
        try {
            while ((line = input.readLine()) != null) {
                if (!line.equals("@")) {
                    builder.append(line).append('\n');
                }
            }
        } finally {
            input.close();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    try {
        Statement stmt = connection.createStatement();
        try {
            stmt.execute(builder.toString());
        } finally {
            DbUtils.close(stmt);
        }
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
    //qRunner.update(connection, builder.toString());
    // TODO: Add an integrity checking functionality. We can check data integrity once data is bulk loaded
}

From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

private void runTwoSqlStatementsWithTwoConnections(PoolingDataSource poolingDataSource)
        throws SQLException, InterruptedException {
    Connection connection = poolingDataSource.getConnection();
    assertNotNull(connection);/*from ww  w  .ja va 2 s.c  o m*/

    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("select current_date()");

    statement = connection.createStatement();
    statement.execute("set session wait_timeout=1");
    assertTrue(resultSet.next());

    connection.close(); // return to pool

    // Wait for 2 seconds
    System.err.print("Sleeping for 2 seconds....");
    Thread.sleep(2 * 1000L);
    System.err.println("Running again now");
    connection = poolingDataSource.getConnection();
    statement = connection.createStatement();
    resultSet = statement.executeQuery("select current_time()");
}

From source file:org.sakaiproject.sitestats.impl.DBHelper.java

private void createIndex(Connection c, String index, String field, String table) throws SQLException {
    notifyIndexesUpdate();/*from   w w w .  j  av  a2  s  .  com*/
    String sql = "create index " + index + " on " + table + "(" + field + ")";
    Statement st = null;
    try {
        st = c.createStatement();
        st.execute(sql);
    } catch (SQLException e) {
        LOG.warn("Failed to execute sql: " + sql, e);
    } finally {
        if (st != null)
            st.close();
    }
}

From source file:fr.calamus.common.db.core.DbPool.java

public void commitTransaction(String key) {
    try {/*www  .ja  v  a  2 s  .com*/
        Statement st = getStatement(key);
        if (st == null || st.isClosed()) {
            st = createStatement(key);
        }
        st.execute("commit");
        transactionCnxKeys.remove(key);
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    //closeStatement();
}

From source file:com.test.HibernateDerbyLockingTest.java

public void testJDBC() throws Exception {
    final DerbyTemplate template = new DerbyTemplate();
    try {/*  ww w.j  av  a2 s .c  om*/
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute(
                        "CREATE TABLE TEST(\n" + "ID CHAR(36) NOT NULL,\n" + "NAME VARCHAR(255)\n" + ")");
            }
        });
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute("INSERT INTO TEST(ID, NAME) VALUES('12345', 'Bob')");
            }
        });

        final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();

        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<?> submit = executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.doWithStatement(new IStatementCallback() {
                    public void execute(Statement statement) throws Exception {
                        ResultSet resultSet = statement.executeQuery(
                                "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rs");
                        while (resultSet.next()) {
                            String id = resultSet.getString("ID");
                            String name = resultSet.getString("NAME");
                        }
                        try {
                            Thread.sleep(2000);
                        } catch (Throwable t) {
                        }
                        System.out.println("one");
                        queue.add("one");
                        try {
                            Thread.sleep(500);
                        } catch (Throwable t) {
                        }
                    }
                });
                return null;
            }
        });
        Thread.sleep(500);
        Future<?> submit2 = executorService.submit(new Callable<Object>() {
            public Object call() throws Exception {
                template.doWithStatement(new IStatementCallback() {
                    public void execute(Statement statement) throws Exception {
                        ResultSet resultSet = statement.executeQuery(
                                "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rr");
                        while (resultSet.next()) {
                            String id = resultSet.getString("ID");
                            String name = resultSet.getString("NAME");
                        }
                        queue.add("two");
                        System.out.println("two");
                    }
                });
                return null;
            }
        });
        submit.get();
        submit2.get();
        assertEquals("one", queue.poll(3, TimeUnit.SECONDS));
        assertEquals("two", queue.poll(3, TimeUnit.SECONDS));
    } finally {
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute("DROP TABLE TEST");
            }
        });
    }
}

From source file:com.googlecode.fascinator.sequences.SequenceService.java

/**
 * Create the given table in the database.
 * /*from w  w w. j  a v  a  2  s .  co m*/
 * @param table
 *            The table to create
 * @throws SQLException
 *             if there was an error during creation, or an unknown table
 *             was specified.
 */
private void createTable(String table) throws SQLException {
    if (table.equals(SEQUENCE_TABLE)) {
        Statement sql = connection().createStatement();
        sql.execute("CREATE TABLE " + SEQUENCE_TABLE + "(sequence_name VARCHAR(255) NOT NULL, "
                + "counter INTEGER NOT NULL," + "PRIMARY KEY (sequence_name))");
        close(sql);
        return;
    }

    throw new SQLException("Unknown table '" + table + "' requested!");
}

From source file:com.ing.connector.newbus.WPendingOverridesImpl.java

/**
 * This method will query the database and create an Odd string that
 * represents the collection of agent overrides.
 *///from   w  w  w  .  ja v  a2 s  . c o  m
public WResult getObject(WObjectKeys keys) {
    String policyId = keys.getStringKey(1);
    String agentSystemSource = keys.getStringKey(2); //JFG2.0
    String companyId = keys.getStringKey(3); //JFG4.0
    String agentParm = keys.getStringKey(4); //CSST400
    String driverSystemSource = getDriver().getSystemSource(); //JFG2.0
    String driverTableType = getDriver().getTableType(); //DIL3.0
    String databaseName = "scldbali"; //DIL3.0
    String procedureName = null; //DIL3.0
    String userType = keys.getStringKey(5);
    String agentName;

    com.ing.connector.Registrar.logInfoMessage("wpendingoverridesimpl - userType" + userType);

    WResult result = new WResult();

    WCollection collection = new WCollection("com.ing.connector.model.WAgentOverrideExt");

    result.setModelObject(collection);

    if (!agentSystemSource.equals(driverSystemSource)) //JFG2.0
    {
        result.setStatus(WResult.OBJECT_NOT_FOUND);
        return result;
    }

    if (userType != null && userType.equalsIgnoreCase("internalUser"))
        databaseName = LookUp.getInstance().getStringProperty("Connector.History.Database");
    ;

    // March 2004 deleted int connNo = line

    Connection con = getConnection();
    // March 2004 removed param

    if (driverTableType.equals(TABLETYPECOPY)) //DIL3.0
    { //DIL3.0

        procedureName = "bali_WAgentOverrides_get_p"; //DIL3.0
    } //DIL3.0
    else //DIL3.0
    { //DIL3.0
        //databaseName = "scldpt";                        //RL-004454 RSD 

        procedureName = "bali_WAgentOverridesImpl"; //DIL3.0
    } //DIL3.0
    com.ing.connector.Registrar.logInfoMessage("wpendingoverridesimpl - databaseName" + databaseName);
    com.ing.connector.Registrar.logInfoMessage("wpendingoverridesimpl - procedureName" + procedureName);
    try {
        Statement stmt = con.createStatement();
        //DIL3.0            stmt.execute("use " + "scldpt");
        stmt.execute("use " + databaseName);
        Registrar.logInfoMessage("exec " + procedureName + " " + policyId + "," + agentParm);
        //DIL3.0            CallableStatement cstmt = con.prepareCall("{call bali_WAgentOverridesImpl(?)}");
        CallableStatement cstmt = con.prepareCall("{call " + procedureName + "(?,?)}"); //CSST400
        cstmt.setString(1, policyId);
        cstmt.setString(2, agentParm); //CSST400

        ResultSet rs = cstmt.executeQuery();

        WDateIsoFormat isoFormat = new WDateIsoFormat();

        while (rs.next()) {

            WAgentOverrideExt single = new WAgentOverrideExt(getDriverName(), getImplTypeName());

            single.setAgentId(rs.getString("agent_number"));
            agentName = new String(rs.getString("agent_name"));
            //RL-009402 - SXL - START
            String formattedAgentName = WStringUtil.formatAgentName(agentName);

            single.setFormattedAgentName(formattedAgentName);

            if (StringUtils.countMatches(agentName, ",") == 2) {
                String lastName = agentName.substring(0, agentName.indexOf(",")).trim();
                String firstName = (agentName.substring(agentName.indexOf(",") + 1, agentName.lastIndexOf(",")))
                        .trim();
                String middleName = (agentName.substring(agentName.lastIndexOf(",") + 1)).trim();
                single.setLastName(lastName);
                single.setFirstName(firstName);
                single.setMiddleName(middleName);
            } else {
                //RL-009402 - SXL - END  
                int i = agentName.indexOf(',');
                if (i != -1) {
                    single.setLastName(agentName.substring(0, i).trim());
                    single.setFirstName(agentName.substring(i + 1).trim());
                } else {
                    single.setLastName(agentName);
                }
            }

            single.setOverridePercent(rs.getDouble("commission_split"));
            single.setContractType(rs.getString("agent_contract_typ"));
            single.setOverrideId(rs.getString("ovr_agent_number")); //CSST400
            single.setOverrideAgentName(rs.getString("ovr_agent_name")); //   KLN/02/13/07//RL-001655    
            single.setLevel(rs.getString("Hierarchy_Type")); //RL-005642 LXJ added
            collection.addElement(single);
        }

        rs.close();
        cstmt.close();
        stmt.close();

        result.setModelObject(collection);

        if (collection.size() == 0) {
            result.setStatus(WResult.OBJECT_NOT_FOUND);
        }

    } catch (SQLException sqle) {
        result.setException(sqle);
        com.ing.connector.Registrar.logError(getClass().getName() + ": " + sqle.getMessage());
    } catch (Exception exc) {
        result.setException(exc);
        com.ing.connector.Registrar.logError(getClass().getName() + ": " + exc.getMessage());
    }

    releaseConnection(con);
    //March 2004 changed param from connNo to con

    return result;

}

From source file:com.mapd.bench.BenchmarkCloud.java

private void storeResults() {
    for (String insertPart : LResult) {
        Statement sin;
        try {/*from w w  w . j  ava2s. c  om*/
            sin = bencherCon.createStatement();
            sin.execute(insertPart);
        } catch (SQLException ex) {
            logger.error("Exception performing insert '" + insertPart + "' text is " + ex.getMessage());
            System.exit(2);
        }
    }
}

From source file:com.jspxcms.core.setup.SetupServlet.java

private void alterDatabaseCharset(String host, String port, String name, String user, String password)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
    Connection connection = getConnection(host, port, name, user, password);
    Statement statement = connection.createStatement();
    String alterDatabase = "alter database " + name + " character set utf8";
    statement.execute(alterDatabase);
    statement.close();//w  w  w.ja  va2 s  .  c om
    connection.close();
}