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.micromux.cassandra.jdbc.PooledTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {

    // configure OPTIONS
    if (!StringUtils.isEmpty(TRUST_STORE)) {
        OPTIONS = String.format("trustStore=%s&trustPass=%s", URLEncoder.encode(TRUST_STORE), TRUST_PASS);
    }/*from w  w w.  j  a  va  2s .  c  o m*/

    Class.forName("com.micromux.cassandra.jdbc.CassandraDriver");
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, "system", OPTIONS));
    Statement stmt = con.createStatement();

    // Drop Keyspace
    String dropKS = String.format("DROP KEYSPACE \"%s\";", KEYSPACE);

    try {
        stmt.execute(dropKS);
    } catch (Exception e) {/* Exception on DROP is OK */
    }

    // Create KeySpace
    String createKS = String.format(
            "CREATE KEYSPACE \"%s\" WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};",
            KEYSPACE);
    stmt.execute(createKS);

    // Create KeySpace
    String useKS = String.format("USE \"%s\";", KEYSPACE);
    stmt.execute(useKS);

    // Create the target Column family
    String createCF = "CREATE COLUMNFAMILY pooled_test (somekey text PRIMARY KEY," + "someInt int" + ") ;";
    stmt.execute(createCF);

    String insertWorld = "UPDATE pooled_test SET someInt = 1 WHERE somekey = 'world'";
    stmt.execute(insertWorld);
}

From source file:com.qubole.quark.server.EndToEndTest.java

public static void setupTables(String dbUrl, String filename)
        throws ClassNotFoundException, SQLException, IOException, URISyntaxException {

    Class.forName("org.h2.Driver");
    Properties props = new Properties();
    props.setProperty("user", "sa");
    props.setProperty("password", "");

    Connection connection = DriverManager.getConnection(dbUrl, props);

    Statement stmt = connection.createStatement();
    java.net.URL url = EndToEndTest.class.getResource("/" + filename);
    java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
    String sql = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");

    stmt.execute(sql);
}

From source file:com.redhat.rhn.common.db.datasource.test.AdvDataSourceTest.java

private static void forceQuery(Connection c, String query) {
    try {//from  w ww  . ja va  2s.  c  om
        Statement stmt = c.createStatement();
        stmt.execute(query);
    } catch (SQLException se) {
        log.warn("Failed to execute query " + query + ": " + se.toString());
    }
}

From source file:io.cloudslang.content.database.services.SQLCommandService.java

public static String executeSqlCommand(final SQLInputs sqlInputs) throws Exception {
    final ConnectionService connectionService = new ConnectionService();
    try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {

        connection.setReadOnly(false);/*from w  w  w  .  j a v  a  2  s . c  o  m*/

        final String dbType = sqlInputs.getDbType();
        if (ORACLE_DB_TYPE.equalsIgnoreCase(dbType)
                && sqlInputs.getSqlCommand().toLowerCase().contains(DBMS_OUTPUT)) {

            final PreparedStatement preparedStatement = connection.prepareStatement(sqlInputs.getSqlCommand());
            preparedStatement.setQueryTimeout(sqlInputs.getTimeout());
            OracleDbmsOutput oracleDbmsOutput = new OracleDbmsOutput(connection);
            preparedStatement.executeQuery();
            sqlInputs.setIUpdateCount(preparedStatement.getUpdateCount());
            preparedStatement.close();
            final String output = oracleDbmsOutput.getOutput();
            oracleDbmsOutput.close();
            return output;
        } else {
            final Statement statement = connection.createStatement(sqlInputs.getResultSetType(),
                    sqlInputs.getResultSetConcurrency());
            statement.setQueryTimeout(sqlInputs.getTimeout());
            try {
                statement.execute(sqlInputs.getSqlCommand());
            } catch (SQLException e) {
                if (SYBASE_DB_TYPE.equalsIgnoreCase(dbType)) {
                    //during a dump sybase sends back status as exceptions.
                    if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dump")) {
                        return SQLUtils.processDumpException(e);
                    } else if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("load")) {
                        return SQLUtils.processLoadException(e);
                    }
                } else {
                    throw e;
                }
            }

            ResultSet rs = statement.getResultSet();
            if (rs != null) {
                ResultSetMetaData rsMtd = rs.getMetaData();
                if (rsMtd != null) {
                    sqlInputs.getLRows().clear();
                    int colCount = rsMtd.getColumnCount();

                    if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) {
                        while (rs.next()) {
                            if (colCount >= 4) {
                                sqlInputs.getLRows().add(rs.getString(4));
                            }
                        }
                    } else {
                        String delimiter = (StringUtils.isNoneEmpty(sqlInputs.getStrDelim()))
                                ? sqlInputs.getStrDelim()
                                : ",";
                        String strRowHolder;
                        while (rs.next()) {
                            strRowHolder = "";
                            for (int i = 1; i <= colCount; i++) {
                                if (i > 1) {
                                    strRowHolder += delimiter;
                                }
                                strRowHolder += rs.getString(i);
                            }
                            sqlInputs.getLRows().add(strRowHolder);
                        }
                    }
                    rs.close();
                }

            }
            //For sybase, when dbcc command is executed, the result is shown in warning message
            else if (dbType.equalsIgnoreCase(SYBASE_DB_TYPE)
                    && sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) {
                SQLWarning warning = statement.getWarnings();
                while (warning != null) {
                    sqlInputs.getLRows().add(warning.getMessage());
                    warning = warning.getNextWarning();
                }
            }

            sqlInputs.setIUpdateCount(statement.getUpdateCount());
        }
    }
    return "Command completed successfully";
}

From source file:net.antidot.sql.model.core.SQLConnector.java

/**
 * Update a database, connected with c, with given request.
 * /* w w w . ja v a2  s . com*/
 * @param c
 * @param query
 * @throws SQLException
 */
public static void updateDatabaseQuery(Connection c, String query) throws SQLException {
    // Get a statement from the connection
    Statement stmt = c.createStatement();
    // Execute the query
    stmt.execute(query);
    // Close statement
    stmt.close();
}

From source file:TerminalMonitor.java

static public void executeStatement(StringBuffer buff) throws SQLException {
    String sql = buff.toString();
    Statement statement = null;

    try {//from  w  w  w . j  a  va  2  s.c  o  m
        statement = connection.createStatement();
        if (statement.execute(sql)) { // true means the SQL was a SELECT
            processResults(statement.getResultSet());
        } else { // no result sets, see how many rows were affected
            int num;

            switch (num = statement.getUpdateCount()) {
            case 0:
                System.out.println("No rows affected.");
                break;

            case 1:
                System.out.println(num + " row affected.");
                break;

            default:
                System.out.println(num + " rows affected.");
            }
        }
    } catch (SQLException e) {
        throw e;
    } finally { // close out the statement
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
            }
        }
    }
}

From source file:com.ery.hadoop.mrddx.hive.HiveOutputFormat.java

/**
 * ddlHQL?/*  w  w w .j  a v  a 2s .  c  o m*/
 * 
 * @param hiveConf hive?
 * @throws SQLException
 */
public static void executeDDLHQL(HiveConfiguration hiveConf, String ddl) throws SQLException {
    if (null == ddl || ddl.trim().length() <= 0) {
        return;
    }
    Connection conn = null;
    try {
        conn = hiveConf.getOutputConnection();
    } catch (ClassNotFoundException e) {
        MRLog.error(LOG, "create hive conn error!");
        e.printStackTrace();
    }

    Statement stat = conn.createStatement();
    try {
        stat.execute(ddl);
    } catch (Exception e) {
        MRLog.errorException(LOG, "execute ddl error, hql:" + ddl, e);
    }

    // 
    close(conn);
}

From source file:demo.learn.shiro.util.SqlUtil.java

/**
 * Gets the HSQL {@link DataSource}./*from   w  w  w .  j  a  va2s  .com*/
 * @return {@link DataSource}.
 */
public synchronized static DataSource getHsqlDataSource() {
    if (!isHsqlInitialized) {
        try {
            String content = FileUtil.getContent(C.HSQL_RESOURCE);
            List<String> sqls = SqlUtil.getSqlStatements(content);

            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;

            try {
                conn = _hsqlDataSource.getConnection();
                stmt = conn.createStatement();
                for (String sql : sqls) {
                    stmt.execute(sql);
                }
                isHsqlInitialized = true;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            } finally {
                SqlUtil.closeQuietly(conn, stmt, rs);
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    return _hsqlDataSource;
}

From source file:jp.co.acroquest.endosnipe.data.dao.AbstractDao.java

/**
 * ?? truncate ???//from   w  w w.j  a  va2s.  c  om
 *
 * @param database ??
 * @param tableName ??
 * @throws SQLException SQL ?????
 */
protected static void truncate(final String database, final String tableName) throws SQLException {
    Connection conn = null;
    Statement stmt = null;
    try {
        conn = getConnection(database);
        stmt = conn.createStatement();

        // ?
        String sql = "truncate table " + tableName;
        stmt.execute(sql);
    } finally {
        SQLUtil.closeStatement(stmt);
        SQLUtil.closeConnection(conn);
    }
}

From source file:com.wavemaker.runtime.data.util.JDBCUtils.java

public static Object runSql(String sql[], String url, String username, String password, String driverClassName,
        Log logger, boolean isDDL) {

    Connection con = getConnection(url, username, password, driverClassName);

    try {//from   w  w  w. j ava 2s  .  com
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            throw new DataServiceRuntimeException(ex);
        }

        Statement s = con.createStatement();

        try {
            try {
                for (String stmt : sql) {
                    if (logger != null && logger.isInfoEnabled()) {
                        logger.info("Running " + stmt);
                    }
                    s.execute(stmt);
                }
                if (!isDDL) {
                    ResultSet r = s.getResultSet();
                    List<Object> rtn = new ArrayList<Object>();
                    while (r.next()) {
                        // getting only the first col is pretty unuseful
                        rtn.add(r.getObject(1));
                    }
                    return rtn.toArray(new Object[rtn.size()]);
                }
            } catch (Exception ex) {
                if (logger != null && logger.isErrorEnabled()) {
                    logger.error(ex.getMessage());
                }
                throw ex;
            }
        } finally {
            try {
                s.close();
            } catch (Exception ignore) {
            }
        }
    } catch (Exception ex) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new DataServiceRuntimeException(ex);
        }
    } finally {
        try {
            con.close();
        } catch (Exception ignore) {
        }
    }

    return null;
}