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:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java

/**
 * {@inheritDoc}/*from  w ww.j ava 2  s  .co  m*/
 */
@Override
public void createUser(String user, String password, String adminUser, String adminPassword)
        throws MojoExecutionException {
    Connection conn = null;
    Statement stmt = null;
    try {
        Properties props = new Properties();
        props.put("user", adminUser);
        props.put("password", adminPassword);
        conn = DriverManager.getConnection(url, props);
        stmt = conn.createStatement();

        if (existsUser(conn, user)) {
            // ???????????????
            String grantSql = "GRANT UNLIMITED TABLESPACE, DATAPUMP_EXP_FULL_DATABASE, DATAPUMP_IMP_FULL_DATABASE TO "
                    + user;
            stmt.execute(grantSql);
            System.err.println("GRANT????:\n" + grantSql);
            return;
        }

        stmt.execute("CREATE USER " + user + " IDENTIFIED BY " + password + " DEFAULT TABLESPACE users");
        String grantSql = "GRANT UNLIMITED TABLESPACE, DATAPUMP_EXP_FULL_DATABASE, DATAPUMP_IMP_FULL_DATABASE TO "
                + user;
        stmt.execute(grantSql);
        System.err.println("GRANT????:\n" + grantSql);

    } catch (SQLException e) {
        throw new MojoExecutionException("CREATE USER?", e);
    } finally {
        StatementUtil.close(stmt);
        ConnectionUtil.close(conn);
    }
}

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

private void excuteSQL(Statement statement, File file) throws IOException, SQLException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
    try {/*from w  w  w.j av  a2 s.  c o  m*/
        String line = null;
        StringBuilder sqlBuilder = new StringBuilder();
        // int i = 0;
        while ((line = reader.readLine()) != null) {
            if (StringUtils.isBlank(line) || line.startsWith("--") || line.startsWith("/*")) {
                continue;
            }
            sqlBuilder.append(line + " ");
            if (line.endsWith(";")) {
                sqlBuilder.setLength(sqlBuilder.length() - 1);
                String sql = sqlBuilder.toString();
                System.out.println(sql);
                statement.execute(sql);
                sqlBuilder.setLength(0);
            }
        }
    } finally {
        reader.close();
    }
}

From source file:migration.Helper.java

/**
 * Sql to string array.//from   w w  w .j a v a 2  s . c o m
 * 
 * @param con
 *            - a valid DriverManager connection is required
 * @param statement
 *            statement is an SQL statement that is executed using
 *            connection con
 * @param column
 *            the column of the query resut to be stored in the retuning
 *            array
 * @return a string array containing the values resulting from the statement
 *         execution, found in column column
 * @throws SQLException
 *             the sQL exception
 */
String[] sqlToStringArray(final Connection con, final String statement, final int column) throws SQLException {
    final String[] ret = new String[this.sqlGetLength(con, statement)];
    final Statement s = con.createStatement();
    s.execute(statement);
    final ResultSet rs = s.getResultSet();
    if (rs != null) {
        int cheat = 0;
        while (rs.next()) {
            ret[cheat++] = rs.getString(column);
        }
    }
    s.close();
    return ret;
}

From source file:io.bibleget.BibleGetDB.java

public boolean setIntOption(String colname, int value) {
    int count;/*from w  w w .  j  a  v a 2  s.c o m*/
    colname = colname.toUpperCase();
    if (instance.connect()) {
        if (!colNames.contains(colname)) {
            boolean result = addColumn(colname, "INT");
            if (result == false) {
                return false;
            }
            //System.out.println("Added "+colname+" column of type INT to OPTIONS table");
            colNames.add(colname);
            colDataTypes.add(Integer.class);
        }
        try {
            Statement stmt = instance.conn.createStatement();
            String sqlexec = "UPDATE OPTIONS SET " + colname + " = " + value + "";
            boolean rowsUpdated = stmt.execute(sqlexec);
            if (rowsUpdated == false) {
                count = stmt.getUpdateCount();
                if (count == -1) {
                    //System.out.println("The result is a ResultSet object or there are no more results."); 
                } else {
                    //should have affected only one row
                    if (count == 1) {
                        stmt.close();
                        instance.disconnect();
                        return true;
                    }
                }
            } else {
                //returns true only when returning a resultset; should not be the case here
            }

        } catch (SQLException ex) {
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return false;
}

From source file:io.bibleget.BibleGetDB.java

public boolean setBooleanOption(String colname, boolean value) {
    int count;/*from   ww  w .j  a  v  a2  s .co m*/
    colname = colname.toUpperCase();
    if (instance.connect()) {
        if (!colNames.contains(colname)) {
            boolean result = addColumn(colname, "BOOLEAN");
            if (result == false) {
                return false;
            }
            //System.out.println("Added "+colname+" column of type BOOLEAN to OPTIONS table");
            colNames.add(colname);
            colDataTypes.add(Boolean.class);
        }
        try {
            Statement stmt = instance.conn.createStatement();
            String sqlexec = "UPDATE OPTIONS SET " + colname + " = " + value + "";
            boolean rowsUpdated = stmt.execute(sqlexec);
            if (rowsUpdated == false) {
                count = stmt.getUpdateCount();
                if (count == -1) {
                    //System.out.println("The result is a ResultSet object or there are no more results."); 
                } else {
                    //should have affected only one row
                    if (count == 1) {
                        stmt.close();
                        instance.disconnect();
                        return true;
                    }
                }
            } else {
                //returns true only when returning a resultset; should not be the case here
            }

        } catch (SQLException ex) {
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return false;
}

From source file:io.bibleget.BibleGetDB.java

public boolean setStringOption(String colname, String value) {
    int count;// w w  w . j  av  a2  s.  com
    colname = colname.toUpperCase();
    if (instance.connect()) {
        if (!colNames.contains(colname)) {
            boolean result = addColumn(colname, "VARCHAR(50)");
            if (result == false) {
                return false;
            }
            //System.out.println("Added "+colname+" column of type VARCHAR(50) to OPTIONS table");
            colNames.add(colname);
            colDataTypes.add(String.class);
        }
        try {
            Statement stmt = instance.conn.createStatement();
            String sqlexec = "UPDATE OPTIONS SET " + colname + " = '" + value + "'";
            boolean rowsUpdated = stmt.execute(sqlexec);
            if (rowsUpdated == false) {
                count = stmt.getUpdateCount();
                if (count == -1) {
                    //System.out.println("The result is a ResultSet object or there are no more results."); 
                } else {
                    //should have affected only one row
                    if (count == 1) {
                        //System.out.println(sqlexec+" seems to have returned true");
                        stmt.close();
                        instance.disconnect();
                        return true;
                    }
                }
            } else {
                //returns true only when returning a resultset; should not be the case here
            }

        } catch (SQLException ex) {
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return false;
}

From source file:migration.Helper.java

/**
 * Sql get length.//from w ww.j  a va  2s .  c  om
 * 
 * @param con
 *            - a valid DriverManager connection is required
 * @param statement
 *            is an SQL statement that is executed using connection con
 * @return the number of rows (int) in the result from the statement
 *         execution
 */
int sqlGetLength(final Connection con, final String statement) {
    int ret = 0;
    try {
        final Statement s = con.createStatement();
        s.execute(statement);
        final ResultSet rs = s.getResultSet();
        if (rs != null) {
            while (rs.next()) {
                ret++;
            }
        }
        s.close(); // EndStatement
    } catch (final SQLException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:it.cnr.icar.eric.server.persistence.rdb.SlotDAO.java

public void deleteByParentIdAndSlots(String parentId, List<?> slots) throws RegistryException {
    Statement stmt = null;

    try {/*w ww . ja  v  a 2s .  co m*/
        stmt = context.getConnection().createStatement();

        String str = "DELETE from " + getTableName() + " WHERE parent = '" + parentId + "' AND (";
        Iterator<?> iter = slots.iterator();

        while (iter.hasNext()) {
            SlotType1 slot = (SlotType1) iter.next();
            String slotName = slot.getName();

            if (iter.hasNext()) {
                str = str + "name_ = '" + Utility.escapeSQLChars(slotName) + "' OR ";
            } else {
                str = str + "name_ = '" + Utility.escapeSQLChars(slotName) + "' )";
            }
        }

        log.trace("stmt = " + str);
        stmt.execute(str);

        int updateCount = stmt.getUpdateCount();

        if (updateCount < slots.size()) {
            throw new SlotNotExistException(parentId);
        }
    } catch (SQLException e) {
        RegistryException exception = new RegistryException(e);
        throw exception;
    } finally {
        closeStatement(stmt);
    }
}

From source file:desktop.olayinka.file.transfer.model.DerbyJDBCHelper.java

public void onStart(Connection mConnection) {
    Statement statement = null;
    ResultSet resultSet = null;//from   ww w.  ja v  a 2s .co m
    try {
        statement = mConnection.createStatement();
        resultSet = statement.executeQuery("SELECT * FROM  app_info");
        resultSet.next();
        mCurrentVersion = resultSet.getLong(1);
        cleanUp(statement, resultSet);
    } catch (SQLException e) {
        e.printStackTrace();
        cleanUp(statement, resultSet);
        try {
            statement = mConnection.createStatement();

            InputStream in = DerbyJDBCHelper.class.getResourceAsStream("/raw/db.sql");
            String[] queries = IOUtils.toString(in).split(";");
            for (String query : queries) {
                query = query.trim();
                if (!query.isEmpty()) {
                    statement.execute(query);
                }
            }

            mConnection.commit();

            mCurrentVersion = 1;

            cleanUp(statement, null);
        } catch (SQLException | IOException e1) {
            e1.printStackTrace();
            cleanUp(statement, null);
            System.exit(1);
        }
    }

}

From source file:com.moss.schematrax.SchemaUpdater.java

private void applyUpdateNoCommit(Connection sqlConnection, DatabaseType databaseType, String schema,
        SchemaUpdate update) throws SchemaUpdateException, DatabaseTypeNotSupportedException {
    // Apply this update
    log.info("Applying update " + update.getId());

    if (update instanceof DynamicSchemaUpdate) {
        JavaUpdateContext ctx = new JavaUpdateContext();
        ctx.setConnection(sqlConnection);
        ctx.setSchemaName(schema);//  w w w. j  a va 2 s  .c o  m
        ctx.setDatabaseType(databaseType);

        DynamicSchemaUpdate dynamicUpdate = (DynamicSchemaUpdate) update;
        dynamicUpdate.setUpdateContext(ctx);
        dynamicUpdate.setSqlBlockParser(this);
    }

    try {
        Reader updateReader = update.getUpdateText(databaseType);

        String[] sqlStatementTexts = parseSqlBlock(updateReader, databaseType);

        Statement statement = sqlConnection.createStatement();

        for (int i = 0; i < sqlStatementTexts.length; i++) {
            String statementText = sqlStatementTexts[i];

            statementText = translateSqlStatement(schema, statementText);

            log.debug("Executing statement:\n" + statementText);
            try {
                statement.execute(statementText);
            } catch (SQLException e) {
                log.info("Passing an SQLException which was caught executing statement: " + statementText, e);
                throw new SchemaUpdateException(e);
            }
        }
    } catch (IOException e) {
        throw new SchemaUpdateException(e);
    } catch (SQLException e) {
        throw new SchemaUpdateException(e);
    }
}