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.silverpeas.components.model.AbstractJndiCase.java

public static void executeDDL(IDatabaseConnection databaseConnection, String filename) {
    Connection connection = null;
    try {//w  w  w .j ava  2 s  .c o m
        connection = databaseConnection.getConnection();
        Statement st = connection.createStatement();
        st.execute(loadDDL(filename));
        connection.commit();
    } catch (Exception e) {
        LoggerFactory.getLogger(AbstractJndiCase.class).error("Error creating tables", e);
    }
}

From source file:com.amazonaws.services.cognito.streams.connector.AmazonCognitoStreamsEnvironmentOptions.java

static void createRedshiftTable(Properties properties) {
    // Ensure our data table exists
    Properties loginProperties = new Properties();
    loginProperties.setProperty("user", getRedshiftUserName());
    loginProperties.setProperty("password", getRedshiftPassword());

    StringBuilder builder = new StringBuilder();
    builder.append("CREATE TABLE IF NOT EXISTS ")
            .append(properties.getProperty(KinesisConnectorConfiguration.PROP_REDSHIFT_DATA_TABLE)).append(" (")
            .append("identityPoolId varchar(128),").append("identityId varchar(128),")
            .append("datasetName varchar(128),").append("operation varchar(64),").append("key varchar(1024),")
            .append("value varchar(4096),").append("op varchar(64),").append("syncCount int,")
            .append("deviceLastModifiedDate timestamp,").append("lastModifiedDate timestamp").append(")");

    Connection conn = null;/*from w  w  w.j av  a2s  .  c  o m*/
    try {
        conn = DriverManager.getConnection(getJDBCConnection(), loginProperties);

        Statement stmt = conn.createStatement();
        stmt.execute(builder.toString());
        stmt.close();
    } catch (SQLException e) {
        LOG.error("Failed to create table.", e);
    } finally {
        try {
            conn.close();
        } catch (SQLException e) {
            LOG.error("Failed close connection.", e);
        }
    }
}

From source file:de.awtools.grooocle.varray.VarrayTest.java

@AfterClass
public static void tearDownClass() throws Exception {
    try {/*www  . jav  a  2 s  . c o  m*/
        if (conn != null) {
            Statement stmt = conn.createStatement();
            stmt.execute("DROP PROCEDURE call_me");
            stmt.execute("DROP TYPE t_string_varray");
        }
    } finally {
        if (conn != null) {
            conn.close();
            conn = null;
        }
    }
}

From source file:com.p6spy.engine.spy.P6TestUtil.java

public static void execute(Connection con, String sql) throws SQLException {
    Statement stmt = null;
    try {/*from  w w w .  j a v a 2  s  .c  o m*/
        stmt = con.createStatement();
        stmt.execute(sql);
    } finally {
        if (stmt != null)
            try {
                stmt.close();
            } catch (Exception e) {
            }
    }
}

From source file:de.awtools.grooocle.varray.VarrayTest.java

@BeforeClass
public static void setUpClass() throws Exception {
    String[] tokens = new String[] { "${user}", "${pwd}", "${url}" };

    String user = System.getProperty("groovy.oracle.test.user");
    String pwd = System.getProperty("groovy.oracle.test.password");
    String url = System.getProperty("groovy.oracle.test.url");

    String[] replacements = new String[] { user, pwd, url };

    DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    String oracleUrl = StringUtils.replaceEach(ORACLE_URL, tokens, replacements);

    conn = DriverManager.getConnection(oracleUrl, user, pwd);
    conn.setAutoCommit(false);/*from   w w  w. j a  v  a 2s  .c  om*/

    Statement stmt = conn.createStatement();
    stmt.execute("CREATE TYPE t_string_varray AS VARRAY(10) OF VARCHAR2(100)");
    stmt.execute(
            "CREATE PROCEDURE call_me(p_strings IN t_string_varray, p_retcode OUT NUMBER) IS BEGIN p_retcode := p_strings.COUNT; END call_me;");
    // Doesnt work:
    //      stmt.execute("CREATE OR REPLACE PACKAGE TEST_PACKAGE IS PROCEDURE log(p_stichmon IN NUMBER); END;");
    //      stmt.execute("CREATE OR REPLACE PACKAGE BODY TEST_PACKAGE IS PROCEDURE log(p_stichmon IN NUMBER) IS BEGIN NULL; END log; END ;");
    stmt.execute("ALTER PROCEDURE call_me COMPILE");
}

From source file:net.firejack.platform.core.utils.OpenFlameDataSource.java

public static boolean ping(DatabaseName type, String host, String port, String user, String password,
        String sid, String schema) {
    try {/*  ww  w.j a  v  a  2 s .co  m*/
        Class.forName(type.getDriver());
        String url;
        if (type == DatabaseName.MySQL) {
            url = type.getDbUrlConnection(DatabaseProtocol.JDBC, host, port);
        } else {
            url = type.getDbSchemaUrlConnection(DatabaseProtocol.JDBC, host, port, sid, schema);
        }

        Connection connection = DriverManager.getConnection(url, user, password);
        if (connection == null) {
            return false;
        }

        Statement statement = connection.createStatement();
        statement.execute(type.getValidate());
        connection.close();
        return true;
    } catch (Exception e) {
        logger.error("Ping to db has failed.");
        return false;
    }
}

From source file:com.sludev.mssqlapplylog.MSSQLHelper.java

/**
 * Restore a Backup Log using a backup file on the file-system.
 * // w ww.j a va2 s  .c o  m
 * @param logPath
 * @param sqlProcessUser Optionally, give this user file-system permissions.  So SQL Server can RESTORE.
 * @param sqlDb The name of the database to restore.
 * @param conn  Open connection
 * @throws SQLException 
 */
public static void restoreLog(final Path logPath, final String sqlProcessUser, final String sqlDb,
        final Connection conn) throws SQLException {
    LOGGER.info(String.format("\nStarting Log restore of '%s'...", logPath));

    StopWatch sw = new StopWatch();

    sw.start();

    if (StringUtils.isNoneBlank(sqlProcessUser)) {
        try {
            FSHelper.addRestorePermissions(sqlProcessUser, logPath);
        } catch (IOException ex) {
            LOGGER.debug(String.format("Error adding read permission for user '%s' to '%s'", sqlProcessUser,
                    logPath), ex);
        }
    }

    String strDevice = logPath.toAbsolutePath().toString();

    String query = String.format("RESTORE LOG %s FROM DISK='%s' WITH NORECOVERY", sqlDb, strDevice);

    Statement stmt = null;

    stmt = conn.createStatement();

    try {
        boolean sqlRes = stmt.execute(query);
    } catch (SQLException ex) {
        LOGGER.error(String.format("Error executing...\n'%s'", query), ex);

        throw ex;
    }

    sw.stop();

    LOGGER.debug(String.format("Query...\n'%s'\nTook %s", query, sw.toString()));
}

From source file:com.uber.hoodie.cli.utils.HiveUtil.java

private static long countRecords(String jdbcUrl, HoodieTableMetaClient source, String srcDb,
        String startDateStr, String endDateStr, String user, String pass) throws SQLException {
    Connection conn = HiveUtil.getConnection(jdbcUrl, user, pass);
    ResultSet rs = null;//  w w  w  . j  a  v a  2  s.co m
    Statement stmt = conn.createStatement();
    try {
        //stmt.execute("set mapred.job.queue.name=<queue_name>");
        stmt.execute("set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat");
        stmt.execute("set hive.stats.autogather=false");
        rs = stmt.executeQuery("select count(`_hoodie_commit_time`) as cnt from " + srcDb + "."
                + source.getTableConfig().getTableName() + " where datestr>'" + startDateStr
                + "' and datestr<='" + endDateStr + "'");
        if (rs.next()) {
            return rs.getLong("cnt");
        }
        return -1;
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:com.uber.hoodie.cli.utils.HiveUtil.java

public static long countRecords(String jdbcUrl, HoodieTableMetaClient source, String dbName, String user,
        String pass) throws SQLException {
    Connection conn = HiveUtil.getConnection(jdbcUrl, user, pass);
    ResultSet rs = null;//from w  w w.ja  va2  s .co m
    Statement stmt = conn.createStatement();
    try {
        //stmt.execute("set mapred.job.queue.name=<queue_name>");
        stmt.execute("set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat");
        stmt.execute("set hive.stats.autogather=false");
        rs = stmt.executeQuery("select count(`_hoodie_commit_time`) as cnt from " + dbName + "."
                + source.getTableConfig().getTableName());
        long count = -1;
        if (rs.next()) {
            count = rs.getLong("cnt");
        }
        System.out.println("Total records in " + source.getTableConfig().getTableName() + " is " + count);
        return count;
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:com.splicemachine.derby.test.framework.SpliceFunctionWatcher.java

public static void executeDrop(String schemaName, String functionName) {
    LOG.trace("executeDrop");
    Connection connection = null;
    Statement statement = null;
    try {/*w w  w.  j a va  2s.com*/
        connection = SpliceNetConnection.getConnection();
        statement = connection.createStatement();
        statement.execute("drop function " + schemaName.toUpperCase() + "." + functionName.toUpperCase());
        connection.commit();
    } catch (Exception e) {
        LOG.error("error Dropping " + e.getMessage());
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
}