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.p6spy.engine.spy.DataSourceTest.java

@Test
public void testGenericDataSourceWithDriverManager() throws Exception {
    // Create and bind the real data source
    // Note: This will get the driver from the DriverManager
    realDs = new TestBasicDataSource();
    realDs.setDriverClassName(driverClass);
    realDs.setUrl(url);/* ww w. ja  v  a2s  .c  o  m*/
    realDs.setUsername(user);
    realDs.setPassword(password);
    realDs.setUseDriverManager(true);
    realDsResource = new Resource("jdbc/realDs", realDs);

    P6TestUtil.setupTestData(realDs);

    // get the data source from JNDI
    DataSource ds = new JndiDataSourceLookup().getDataSource("jdbc/spyDs");
    assertNotNull("JNDI data source not found", ds);

    // get the connection
    con = ds.getConnection();

    // verify that the connection class is a proxy
    assertTrue("Connection is not a proxy", ProxyFactory.isProxy(con));

    Statement stmt = con.createStatement();
    stmt.execute("select 1 from customers");
    stmt.close();
    assertTrue(((P6TestLogger) P6LogQuery.getLogger()).getLastEntry().indexOf("select 1") != -1);
    assertEquals("Incorrect number of spy log messages", 1,
            ((P6TestLogger) P6LogQuery.getLogger()).getLogs().size());
}

From source file:net.tirasa.connid.bundles.soap.wssample.DefaultContentLoader.java

@Override
public void contextInitialized(final ServletContextEvent sce) {
    final WebApplicationContext springContext = WebApplicationContextUtils
            .getWebApplicationContext(sce.getServletContext());

    if (springContext == null) {
        LOG.error("Invalid Spring context");
        return;/*w ww. j  a va2  s . c  om*/
    }

    final DataSource dataSource = springContext.getBean(DataSource.class);
    localDataSource = dataSource;

    final DefaultDataTypeFactory dbUnitDataTypeFactory = (DefaultDataTypeFactory) springContext
            .getBean("dbUnitDataTypeFactory");

    final Connection conn = DataSourceUtils.getConnection(dataSource);

    // create schema
    final StringBuilder statement = new StringBuilder();

    final InputStream dbschema = DefaultContentLoader.class.getResourceAsStream(DBSCHEMA);

    final BufferedReader buff = new BufferedReader(new InputStreamReader(dbschema));

    String line = null;
    try {
        while ((line = buff.readLine()) != null) {
            if (!line.isEmpty() && !line.startsWith("--")) {
                statement.append(line);
            }
        }
    } catch (IOException e) {
        LOG.error("Error reading file " + DBSCHEMA, e);
        return;
    }

    Statement st = null;
    try {
        st = conn.createStatement();
        st.execute(statement.toString());
    } catch (SQLException e) {
        LOG.error("Error creating schema:\n" + statement.toString(), e);
        return;
    } finally {
        try {
            st.close();
        } catch (Throwable t) {
            // ignore exception
        }
    }

    try {
        IDatabaseConnection dbUnitConn = new DatabaseConnection(conn);

        final DatabaseConfig config = dbUnitConn.getConfig();
        config.setProperty("http://www.dbunit.org/properties/datatypeFactory", dbUnitDataTypeFactory);

        boolean existingData = false;
        final IDataSet existingDataSet = dbUnitConn.createDataSet();
        for (final ITableIterator itor = existingDataSet.iterator(); itor.next() && !existingData;) {
            existingData = (itor.getTable().getRowCount() > 0);
        }

        final FlatXmlDataSetBuilder dataSetBuilder = new FlatXmlDataSetBuilder();
        dataSetBuilder.setColumnSensing(true);
        final IDataSet dataSet = dataSetBuilder.build(getClass().getResourceAsStream("/content.xml"));
        DatabaseOperation.REFRESH.execute(dbUnitConn, dataSet);
    } catch (Throwable t) {
        LOG.error("Error loding default content", t);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }
}

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

@Override
protected void starting(Description description) {
    LOG.trace("Starting");
    executeDrop(roleName.toUpperCase());
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;//from ww  w.j ava  2 s .c o  m
    try {
        connection = SpliceNetConnection.getConnection();
        statement = connection.createStatement();
        statement.execute(String.format("create role %s", roleName));
        connection.commit();
    } catch (Exception e) {
        LOG.error("Role statement is invalid ");
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
    super.starting(description);
}

From source file:de.langmi.spring.batch.examples.readers.support.CompositeCursorItemReaderTest.java

/**
 * Create a table and fill with some test data.
 *
 * @param dataSource//from  ww w .  jav  a  2  s  .  c  o  m
 * @throws Exception 
 */
private void createTableWithTestData(final DataSource dataSource) throws Exception {
    // create table
    Connection conn = dataSource.getConnection();
    Statement st = conn.createStatement();
    st.execute(CREATE_TEST_TABLE);
    conn.commit();
    st.close();
    conn.close();

    // fill with values
    conn = dataSource.getConnection();
    // prevent auto commit for batching
    conn.setAutoCommit(false);
    PreparedStatement ps = conn.prepareStatement(INSERT);
    // fill with values
    for (int i = 0; i < EXPECTED_COUNT; i++) {
        ps.setString(1, String.valueOf(i));
        ps.addBatch();
    }
    ps.executeBatch();
    conn.commit();
    ps.close();
    conn.close();
}

From source file:net.duckling.falcon.api.boostrap.BootstrapDao.java

private void execute(Connection conn, String sql) {
    Statement statement = null;
    try {//w w  w.j  a v a  2  s. c  o m
        statement = conn.createStatement();
        statement.execute(sql);
    } catch (SQLException e) {
        throw new WrongSQLException(e.getMessage());
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new WrongSQLException(e.getMessage());
            }
        }
    }
}

From source file:de.klemp.middleware.controller.Controller.java

/**
 * This method deletes all saved rows in the database.
 *///from  w w  w  .j  a  v  a  2  s .c o  m
public static void deleteController() {
    controller.clear();
    createDBConnection();
    Statement st;
    try {
        st = conn.createStatement();
        st.execute("delete from \"Controller\";");
    } catch (SQLException e) {
        logger.error("SQL Exception", e);
    }

    closeDBConnection();
}

From source file:com.solace.data.BaseTest.java

public void setUp() throws Exception {
    try {// w w w.  j  a v a  2s.  co  m
        LOGGER.info("Starting in-memory HSQL database for unit tests");
        Class.forName("org.hsqldb.jdbcDriver");
        cnxn = DriverManager.getConnection("jdbc:hsqldb:mem:test", "sa", "");

    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        fail("Exception during HSQL database startup.");
    }

    try {
        BufferedReader r = new BufferedReader(
                new InputStreamReader(getClass().getClassLoader().getResourceAsStream((INPUT_SQL_FILE))));

        StringBuffer sb = new StringBuffer();

        String s = null;

        while ((s = r.readLine()) != null)
            sb.append(s);

        r.close();

        Statement st = cnxn.createStatement();

        LOGGER.info("Executing/n" + sb.toString());

        if (st.execute(sb.toString()))
            LOGGER.debug("successfully created.");
        else
            LOGGER.debug("bombed");

        st.close();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:chh.utils.db.source.common.JdbcClient.java

public void executeSql(String sql) {
    Connection connection = null;
    try {/*from  ww  w . j  ava  2 s  .com*/
        connection = connectionProvider.getConnection();
        Statement statement = connection.createStatement();
        statement.execute(sql);
    } catch (SQLException e) {
        throw new RuntimeException("Failed to execute SQL", e);
    } finally {
        closeConnection(connection);
    }
}

From source file:kr.co.bitnine.octopus.schema.metamodel.OctopusMetaModelTest.java

@Before
public void setUp() throws Exception {
    metaMemDb = new MemoryDatabase("meta");
    metaMemDb.start();/*www.  j a  v a2 s  .  co m*/

    embeddedElasticsearchServer = new EmbeddedElasticsearchServer();
    client = embeddedElasticsearchServer.getClient();
    client.prepareIndex(databaseName, tableName).setId("99").setSource(buildPeopleJson("LEE", 35)).execute()
            .actionGet();

    // The refresh API allows to explicitly refresh one or more index,
    // making all operations performed since the last refresh available for
    // search
    embeddedElasticsearchServer.getClient().admin().indices().prepareRefresh().execute().actionGet();
    System.out.println("Embedded ElasticSearch server created!");

    Configuration conf = new OctopusConfiguration();
    conf.set("metastore.jdo.connection.drivername", MemoryDatabase.DRIVER_NAME);
    conf.set("metastore.jdo.connection.URL", metaMemDb.connectionString);
    conf.set("metastore.jdo.connection.username", "");
    conf.set("metastore.jdo.connection.password", "");

    MetaStore metaStore = MetaStores.newInstance(conf.get("metastore.class"));
    metaStoreService = new MetaStoreService(metaStore, new StdoutUpdateLoggerFactory());
    metaStoreService.init(conf);
    metaStoreService.start();

    MetaContext metaContext = metaStore.getMetaContext();
    MetaUser user = metaContext.createUser("octopus", "bitnine");
    metaContext.addSystemPrivileges(Arrays.asList(SystemPrivilege.values()), Arrays.asList(user.getName()));

    connectionManager = new ConnectionManager(metaStore);
    connectionManager.init(conf);
    connectionManager.start();

    schemaManager = SchemaManager.getSingletonInstance(metaStore);
    schemaManager.init(conf);
    schemaManager.start();

    SessionFactory sessFactory = new SessionFactoryImpl(metaStore, connectionManager, schemaManager);
    sessionServer = new SessionServer(sessFactory);
    sessionServer.init(conf);
    sessionServer.start();

    Connection conn = getConnection("octopus", "bitnine");
    Statement stmt = conn.createStatement();
    stmt.execute("ALTER SYSTEM ADD DATASOURCE \"" + datasourceName + "\" CONNECT TO '" + connectionString
            + "' USING '" + driverName + "'");
    stmt.close();
    conn.close();
}

From source file:com.github.brandtg.switchboard.TestMysqlLogServer.java

@BeforeMethod
public void beforeMethod() throws Exception {
    // Reset and setup local MySQL
    try (Connection conn = DriverManager.getConnection(jdbc, "root", "")) {
        Statement stmt = conn.createStatement();
        stmt.execute("RESET MASTER");
        stmt.execute("GRANT ALL ON *.* TO 'switchboard'@'localhost' IDENTIFIED BY 'switchboard'");
        stmt.execute("DROP TABLE IF EXISTS simple");
        stmt.execute("CREATE TABLE simple (k INT, v INT)");
    }//from  ww  w  .jav  a  2  s .  co  m

    // Start server
    MysqlLogServerConfig config = new MysqlLogServerConfig();
    server = DropWizardApplicationRunner.createServer(config, MysqlLogServer.class);
    server.start();
}