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:eu.peppol.persistence.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

private void runTwoSqlStatementsWithTwoConnections(PoolingDataSource poolingDataSource)
        throws SQLException, InterruptedException {

    Connection connection = poolingDataSource.getConnection();
    if (connection.getMetaData().getDatabaseProductName().toLowerCase().contains("mysql")) {
        assertNotNull(connection);//from   w ww .  j a  v a  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:com.dattack.dbtools.drules.engine.SourceExecutor.java

private ResultSet executeStatement(final Statement statement, final String sql) throws SQLException {

    LOGGER.info("Executing SQL sentence [{}@{}]: {}", Thread.currentThread().getName(), sourceBean.getId(),
            sql);//from w w  w. j a  va  2 s  . co m

    final boolean isResultSet = statement.execute(sql);

    if (isResultSet) {
        return statement.getResultSet();
    }

    return null;
}

From source file:com.emergya.persistenceGeo.dao.impl.PostgisDBManagementDaoHibernateImpl.java

@Override
public void duplicateLayerTable(final String sourceTable, final String destinationTable) {
    SessionFactoryImplementor sfi = (SessionFactoryImplementor) getSessionFactory();
    final String schema = sfi.getSettings().getDefaultSchemaName();
    final String copyTableSql = MessageFormat.format(DUPLICATE_TABLE_SQL, schema, destinationTable,
            sourceTable);/*from w  w  w  .j av  a 2  s .c o  m*/

    final String updateGeometryColumnSql = String.format(UPDATE_GEOMETRY_COLUMN_SQL, destinationTable,
            sourceTable);

    getSession().doWork(new Work() {

        @Override
        public void execute(Connection connection) throws SQLException {
            Statement stmt = connection.createStatement();
            stmt.execute(copyTableSql);
            stmt.execute(updateGeometryColumnSql);
            ResultSet pksRS = connection.getMetaData().getPrimaryKeys(null, schema, sourceTable);

            if (pksRS.first()) {
                String primaryKey = pksRS.getString("COLUMN_NAME");

                String createPkSql = MessageFormat.format(ADD_TABLE_PK, schema, destinationTable, primaryKey);

                stmt.execute(createPkSql);
            }
        }
    });

    getSession().flush();
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java

@Test
public void testInsertSingleRecord() throws Exception {
    Statement s = methodWatcher.getStatement();
    s.execute("insert into S (name) values ('gdavis')");
    ResultSet rs = methodWatcher.executeQuery("select * from S");
    int count = 0;
    while (rs.next()) {
        count++;//from  ww w .  j ava 2 s.c o m
        Assert.assertNotNull(rs.getString(1));
    }
    Assert.assertEquals("Incorrect Number of Results Returned", 1, count);
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java

@Test
public void testInsertMultipleRecords() throws Exception {
    Statement s = methodWatcher.getStatement();
    s.execute("insert into T(name) values ('gdavis'),('mzweben'),('rreimer')");
    List<String> correctNames = Arrays.asList("gdavis", "mzweben", "rreimer");
    Collections.sort(correctNames);
    ResultSet rs = methodWatcher.executeQuery("select * from T");
    List<String> names = new ArrayList<>();
    while (rs.next()) {
        names.add(rs.getString(1));// w w w.  j a  v a 2s. c  o m
    }
    Collections.sort(names);
    Assert.assertEquals("returned named incorrect!", correctNames, names);
}

From source file:com.amazonaws.services.kinesis.connectors.redshift.RedshiftManifestEmitter.java

/**
 * Helper function to execute SQL Statement with no results. Attempts to execute the statement
 * redshiftRetryLimit times./*from   w  w  w.  j a  v a  2  s . c  o  m*/
 * 
 * @param statement
 * @throws IOException
 */
private void executeStatement(Connection conn, String statement) throws IOException {
    try {
        Statement stmt = conn.createStatement();
        stmt.execute(statement);
        stmt.close();
        return;
    } catch (SQLException e) {
        LOG.error("Amazon S3 endpoint set to: " + s3Endpoint);
        LOG.error("Error executing statement: " + statement, e);
        throw new IOException(e);
    }
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java

@Test
public void testInsertMultipleRecordsWithSameLength() throws Exception {
    /*Regression test for DB-1278*/
    Statement s = methodWatcher.getStatement();
    s.execute("insert into SAME_LENGTH (name) values ('ab'),('de'),('fg')");
    List<String> correctNames = Arrays.asList("ab", "de", "fg");
    Collections.sort(correctNames);
    ResultSet rs = methodWatcher.executeQuery("select * from SAME_LENGTH");
    List<String> names = new ArrayList<>();
    while (rs.next()) {
        names.add(rs.getString(1));//from ww  w  .  j a va 2 s.c  o m
    }
    Collections.sort(names);
    Assert.assertEquals("returned named incorrect!", correctNames, names);
}

From source file:com.mirth.connect.server.util.DatabaseUtil.java

public static void executeScript(String script, boolean ignoreErrors) throws Exception {
    SqlSessionManager sqlSessionManger = SqlConfig.getSqlSessionManager();

    Connection conn = null;/* w  ww .  jav  a 2s  .c o m*/
    ResultSet resultSet = null;
    Statement statement = null;

    try {
        sqlSessionManger.startManagedSession();
        conn = sqlSessionManger.getConnection();

        /*
         * Set auto commit to false or an exception will be thrown when trying to rollback
         */
        conn.setAutoCommit(false);

        statement = conn.createStatement();

        Scanner s = new Scanner(script);

        while (s.hasNextLine()) {
            StringBuilder sb = new StringBuilder();
            boolean blankLine = false;

            while (s.hasNextLine() && !blankLine) {
                String temp = s.nextLine();

                if (temp.trim().length() > 0)
                    sb.append(temp + " ");
                else
                    blankLine = true;
            }

            // Trim ending semicolons so Oracle doesn't throw
            // "java.sql.SQLException: ORA-00911: invalid character"
            String statementString = StringUtils.removeEnd(sb.toString().trim(), ";");

            if (statementString.length() > 0) {
                try {
                    statement.execute(statementString);
                    conn.commit();
                } catch (SQLException se) {
                    if (!ignoreErrors) {
                        throw se;
                    } else {
                        logger.error("Error was encountered and ignored while executing statement: "
                                + statementString, se);
                        conn.rollback();
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(resultSet);
        DbUtils.closeQuietly(conn);
        sqlSessionManger.close();
    }
}

From source file:it.unibas.spicygui.controllo.provider.intermediatezone.MyEditProviderConst.java

public String verificaDati() throws DAOException, SQLException {
    String type = null;/*from  w  w  w.  j av a  2s .co  m*/
    if (this.dialog.getJRadioButtonFunction().isSelected()) {
        if (this.dialog.getJComboBoxFunction().getSelectedItem().toString().equalsIgnoreCase("newId()")) {
            String sequence = this.dialog.getTextSequenceName().getText().trim();
            if (SpicyEngineConstants.GET_ID_FROM_DB.get(sequence) != null)
                SpicyEngineConstants.TEMP_DB_PROPERTIES = SpicyEngineConstants.GET_ID_FROM_DB.get(sequence);

            caratteristiche.setCostante(this.dialog.getJComboBoxFunction().getSelectedItem() + "_" + sequence);

            if (this.dialog.getJRadioButtonConstant().isSelected()) {
                SpicyEngineConstants.OFFSET_MAPPING.put(sequence, this.dialog.getOffsetText().getText().trim());
                type = "constant";
            } else if (this.dialog.getJRadioButtonDatabase().isSelected()) {
                if (SpicyEngineConstants.TEMP_DB_PROPERTIES != null) {
                    Connection connection = connectToDb();
                    Statement statement = connection.createStatement();
                    if (SpicyEngineConstants.TEMP_DB_PROPERTIES.getFunction().equalsIgnoreCase("max")) {
                        statement.execute("SELECT MAX(\"" + SpicyEngineConstants.TEMP_DB_PROPERTIES.getColumn()
                                + "\") FROM \"" + SpicyEngineConstants.TEMP_DB_PROPERTIES.getTable() + "\";");
                    }
                    ResultSet rs = statement.getResultSet();
                    if (rs.next()) {
                        SpicyEngineConstants.OFFSET = String.valueOf(rs.getInt(1));
                    } else {
                        SpicyEngineConstants.OFFSET = "0";
                    }
                    SpicyEngineConstants.OFFSET_MAPPING.put(sequence, SpicyEngineConstants.OFFSET);
                    SpicyEngineConstants.GET_ID_FROM_DB.put(sequence, SpicyEngineConstants.TEMP_DB_PROPERTIES);
                    SpicyEngineConstants.TEMP_DB_PROPERTIES = null;
                    type = "getId()";
                } else {
                    if (dialog.getReturnStatus() == ConstantDialog.RET_OK) {
                        JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
                                "Please setup the database configuration!", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                if (dialog.getReturnStatus() == ConstantDialog.RET_OK) {
                    JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
                            "Please select offset source input!", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else if (this.dialog.getJComboBoxFunction().getSelectedItem().toString().equalsIgnoreCase("date()")) {
            type = "date";
            caratteristiche.setCostante(this.dialog.getJComboBoxFunction().getSelectedItem());
        } else {
            type = "datetime";
            caratteristiche.setCostante(this.dialog.getJComboBoxFunction().getSelectedItem());
        }
    }
    if (this.dialog.getJRadioButtonNumber().isSelected()) {
        type = "number";
        Double.parseDouble((String) caratteristiche.getCostante());
    }
    if (this.dialog.getJRadioButtonString().isSelected()) {
        type = "string";
        String valoreCostante = (String) caratteristiche.getCostante();
        caratteristiche.setCostante(Utility.sostituisciVirgolette(valoreCostante));
    }
    caratteristiche.setType(type);
    return type;
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java

@Test
public void testInsertFromSubselect() throws Exception {
    Statement s = methodWatcher.getStatement();
    s.execute("insert into G values('sfines')");
    s.execute("insert into G values('jzhang')");
    s.execute("insert into G values('jleach')");
    methodWatcher.commit();/*w ww  . j av  a  2  s  .  c  o m*/
    List<String> correctNames = Arrays.asList("sfines", "jzhang", "jleach");
    Collections.sort(correctNames);
    //copy that data into table t
    s = methodWatcher.getStatement();
    s.execute("insert into B (name) select name from G");
    methodWatcher.commit();
    ResultSet rs = methodWatcher.executeQuery("select * from B");
    List<String> names = new ArrayList<>();
    while (rs.next()) {
        names.add(rs.getString(1));
    }
    Collections.sort(names);
    Assert.assertEquals("returned named incorrect!", correctNames, names);
    methodWatcher.commit();
}