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.splicemachine.derby.test.framework.SpliceViewWatcher.java

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

From source file:com.micromux.cassandra.jdbc.SpashScreenTest.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);
    }/* w  ww. j ava2s  .  c  o  m*/

    Class.forName("com.micromux.cassandra.jdbc.CassandraDriver");
    con = DriverManager.getConnection(
            String.format("jdbc:cassandra://%s:%d/%s?%s&version=3.0.0", 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 = con.createStatement();
    stmt.execute(createKS);

    // Use Keyspace
    String useKS = String.format("USE %s;", KEYSPACE);
    stmt.execute(useKS);

    // Create the target Column family
    String create = "CREATE COLUMNFAMILY Test (KEY text PRIMARY KEY, a bigint, b bigint) ;";
    stmt = con.createStatement();
    stmt.execute(create);
    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager
            .getConnection(String.format("jdbc:cassandra://%s:%d/%s?%s", HOST, PORT, KEYSPACE, OPTIONS));
}

From source file:com.surveypanel.dao.DBTestCase.java

/**
 * Executes a SQL script./*  w  w w  .j  ava2s  .  c o m*/
 *
 * @param con database connection.
 * @param resource an input stream for the script to execute.
 * @param autoreplace automatically replace jiveVersion with ofVersion
 * @throws IOException if an IOException occurs.
 * @throws SQLException if an SQLException occurs.
 */
private static void executeSQLScript(Connection con, InputStream resource) throws IOException, SQLException {
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(resource));
        boolean done = false;
        while (!done) {
            StringBuilder command = new StringBuilder();
            while (true) {
                String line = in.readLine();
                if (line == null) {
                    done = true;
                    break;
                }
                // Ignore comments and blank lines.
                if (isSQLCommandPart(line)) {
                    command.append(" ").append(line);
                }
                if (line.trim().endsWith(";")) {
                    break;
                }
            }
            // Send command to database.
            if (!done && !command.toString().equals("")) {
                try {
                    String cmdString = command.toString();
                    Statement stmt = con.createStatement();
                    stmt.execute(cmdString);
                    stmt.close();
                } catch (SQLException e) {
                    // Lets show what failed
                    logger.error("SchemaManager: Failed to execute SQL:\n" + command.toString());
                    throw e;
                }
            }
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

From source file:de.mendelson.comm.as2.database.DBDriverManager.java

/**Creates a new locale database
 * @return true if it was created successfully
 * @param DB_TYPE of the database that should be created, as defined in this class
 *///from w w w .  jav  a2  s .  c  o m
public static boolean createDatabase(final int DB_TYPE) {
    // It will be create automatically if it does not yet exist
    // the given files in the URL is the name of the database
    // "sa" is the user name and "" is the (empty) password
    StringBuilder message = new StringBuilder("Creating database ");
    String createResource = null;
    int dbVersion = 0;
    if (DB_TYPE == DBDriverManager.DB_CONFIG) {
        message.append("CONFIG");
        dbVersion = AS2ServerVersion.getRequiredDBVersionConfig();
        createResource = SQLScriptExecutor.SCRIPT_RESOURCE_CONFIG;
    } else if (DB_TYPE == DBDriverManager.DB_RUNTIME) {
        message.append("RUNTIME");
        dbVersion = AS2ServerVersion.getRequiredDBVersionRuntime();
        createResource = SQLScriptExecutor.SCRIPT_RESOURCE_RUNTIME;
    } else if (DB_TYPE != DBDriverManager.DB_DEPRICATED) {
        throw new RuntimeException("Unknown DB type requested in DBDriverManager.");
    }
    Logger.getLogger(AS2Server.SERVER_LOGGER_NAME).info(message.toString());
    Connection connection = null;
    try {
        connection = DriverManager.getConnection("jdbc:hsqldb:" + DBDriverManager.getDBName(DB_TYPE), "sa", "");
        Statement statement = connection.createStatement();
        statement.execute("ALTER USER " + DB_USER_NAME.toUpperCase() + " SET PASSWORD '" + DB_PASSWORD + "'");
        statement.close();
        SQLScriptExecutor executor = new SQLScriptExecutor();
        executor.create(connection, createResource, dbVersion);
        Logger.getLogger(AS2Server.SERVER_LOGGER_NAME).info("Database created.");
    } catch (Exception e) {
        throw new RuntimeException("Database not created: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                Logger.getLogger(AS2Server.SERVER_LOGGER_NAME)
                        .severe("Database creation failed: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
    return (true);
}

From source file:com.micromux.cassandra.jdbc.DataSourceTest.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);
    }//w ww .ja  va  2s.com

    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);
    //        String createKS = String.format("CREATE KEYSPACE %s WITH strategy_class = SimpleStrategy AND strategy_options:replication_factor = 1;",KEYSPACE);
    stmt.execute(createKS);
}

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

/**
 * ??????????<br />//w ww .  ja v a  2s  .com
 *
 * @param conn ?
 * @param table ??
 * @throws SQLException SQL ?????
 */
protected static void deleteAll(final Connection conn, final String table) throws SQLException {
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        stmt.execute("delete from " + table);
    } finally {
        SQLUtil.closeStatement(stmt);
    }
}

From source file:org.mitre.jdbc.datasource.H2DataSourceFactory.java

protected static void executeSql(String sql, Connection connection) throws SQLException {
    Statement statement = connection.createStatement();
    statement.execute(sql);/*w  w  w  .  ja  v a2 s . c  om*/
}

From source file:ProxyAuthTest.java

private static void exStatement(String query) throws Exception {
    Statement stmt = con.createStatement();
    stmt.execute(query);
    if (!noClose) {
        stmt.close();//from  w  w  w .j  ava 2s  . c  om
    }
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicUpdateTest.java

@AfterClass
public static void dispose() throws Exception {
    if (GeoServerTests.skipTest()) {
        return;/*w  w w .ja v  a2s.  c o m*/
    }

    // clean up GS
    GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(GeoServerTests.URL, GeoServerTests.UID,
            GeoServerTests.PWD);
    publisher.removeCoverageStore(WORKSPACE, STORE, true);

    // remove created dir
    FileUtils.deleteDirectory(BASE_DIR);

    // delete table
    if (PostGisDataStoreTests.existsPostgis()) {

        // props
        final Properties props = ImageMosaicProperties
                .getPropertyFile(PostGisDataStoreTests.getDatastoreProperties());

        // delete
        Class.forName("org.postgresql.Driver");
        Connection connection = DriverManager.getConnection(
                "jdbc:postgresql://" + props.getProperty("host") + ":" + props.getProperty("port") + "/"
                        + props.getProperty("database"),
                props.getProperty("user"), props.getProperty("passwd"));
        Statement st = connection.createStatement();
        st.execute("DROP TABLE IF EXISTS " + STORE);
        st.close();
        connection.close();
    }

}

From source file:com.freemedforms.openreact.db.DbSchema.java

/**
 * Attempt to run a database patch./*from  w w  w  .  j  av a 2 s.  com*/
 * 
 * @param patchFilename
 * @return Success.
 * @throws SQLException
 */
public static boolean applyPatch(String patchFilename) throws SQLException {
    Connection c = Configuration.getConnection();

    String patch = null;

    Scanner scanner;
    try {
        scanner = new Scanner(new File(patchFilename)).useDelimiter("\\Z");
        patch = scanner.next();
        scanner.close();
    } catch (FileNotFoundException ex) {
        log.error(ex);
        return false;
    }

    Statement cStmt = c.createStatement();
    boolean status = false;
    try {
        log.debug("Using patch length = " + patch.length());
        cStmt.execute(patch);
        // cStmt = c.prepareStatement(patch);
        // cStmt.execute();
        log.info("Patch succeeded");
        status = true;
    } catch (NullPointerException npe) {
        log.error("Caught NullPointerException", npe);
    } catch (Throwable e) {
        log.error(e.toString());
    } finally {
        DbUtil.closeSafely(cStmt);
        DbUtil.closeSafely(c);
    }

    return status;
}