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.evolveum.midpoint.tools.ninja.ImportDDL.java

private void readScript(File script, BufferedReader reader, Connection connection) throws IOException {
    System.out.println("Reading DDL script file '" + script.getAbsolutePath() + "'.");
    reader = new BufferedReader(new InputStreamReader(new FileInputStream(script), "utf-8"));
    StringBuilder query = new StringBuilder();
    String line;/*from  ww  w. j  a v  a2s . co m*/
    while ((line = reader.readLine()) != null) {
        //skip comments
        if (line.length() == 0 || line.length() > 0 && line.charAt(0) == '-') {
            continue;
        }

        if (query.length() != 0) {
            query.append(' ');
        }
        query.append(line.trim());

        //If one command complete
        if (query.charAt(query.length() - 1) == ';') {
            query.deleteCharAt(query.length() - 1);
            try {
                String queryStr = query.toString();
                System.out.println("Executing query: " + queryStr);

                Statement stmt = connection.createStatement();
                stmt.execute(queryStr);
                stmt.close();
            } catch (SQLException ex) {
                System.out.println("Exception occurred during SQL statement '" + query.toString()
                        + "' execute, reason: " + ex.getMessage());
            }
            query = new StringBuilder();
        }
    }
}

From source file:net.refractions.udig.catalog.internal.postgis.ui.PostgisDatabaseConnectionRunnable.java

public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {

    try {//from  ww  w.j  a  va 2 s . c  om

        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put(DBTYPE.key, (Serializable) new PostgisServiceDialect().dbType);
        params.put(HOST.key, host);
        params.put(PORT.key, port);
        params.put(USER.key, username);
        params.put(PASSWD.key, password);
        params.put(DATABASE.key, "template1");

        BasicDataSource source = PostgisServiceExtension2.getFactory().createDataSource(params);
        Connection connection = source.getConnection();
        try {

            Statement statement = connection.createStatement();
            if (statement.execute("SELECT datname FROM pg_database")) {
                ResultSet resultSet = statement.getResultSet();
                while (resultSet.next()) {
                    databaseNames.add(resultSet.getString("datname"));
                }
            }
            statement.close();
        } finally {
            if (connection != null) {
                connection.close();
            }
            if (source != null) {
                source.close();
            }
        }
    } catch (SQLException e) {
        checkSqlException(e);
    } catch (IOException e) {
        if (e.getCause() instanceof SQLException) {
            checkSqlException((SQLException) e.getCause());
        } else {
            PostgisPlugin.log("Error connecting to datasource", e);
            result = "Unrecognized connection failure.  Check parameters and database.";
        }
    }
    ran = true;
}

From source file:be.fgov.kszbcss.rhq.websphere.component.jdbc.db2.pool.ConnectionContextImpl.java

void testConnection() throws SQLException {
    execute(new Query<Void>() {
        public Void execute(Connection connection) throws SQLException {
            Statement statement = connection.createStatement();
            try {
                statement.execute("SELECT 1 FROM SYSIBM.SYSDUMMY1");
            } finally {
                statement.close();//from w  w w  .j  a va 2 s.  c  o m
            }
            return null;
        }
    });
}

From source file:de.langmi.spring.batch.examples.readers.jdbc.JdbcPagingItemReaderTests.java

/**
 * Shutdown HSQLDB properly.//  ww w.  ja va2s  . c om
 *
 * @throws Exception 
 */
@After
public void tearDown() throws Exception {
    Connection conn = dataSource.getConnection();
    Statement st = conn.createStatement();
    st.execute("SHUTDOWN");
    conn.commit();
    st.close();
}

From source file:com.arsmentis.cordova.jdbc.Jdbc.java

private JSONArray execute(String sql) throws SQLException, JSONException {
    if (connection == null) {
        throw new SQLException("Not connected");
    }/*from   ww w  .  j av  a 2 s.c  o  m*/

    JSONArray results = new JSONArray();
    Statement statement = connection.createStatement();

    if (statement.execute(sql)) {
        ResultSet resultSet = statement.getResultSet();
        ResultSetMetaData columns = resultSet.getMetaData();

        while (resultSet.next()) {
            JSONObject row = new JSONObject();

            for (int i = 1; i <= columns.getColumnCount(); i++) {
                row.put(columns.getColumnName(i), resultSet.getObject(i));
            }
            results.put(row);
        }

        resultSet.close();
    }

    statement.close();

    return results;
}

From source file:com.splicemachine.test_tools.TableCreator.java

private void createTable() throws SQLException {
    String baseSql = createSql;/*from w w  w.jav  a 2  s  . co m*/
    if (constraints != null) {
        int lastParenthesis = baseSql.lastIndexOf(")");
        baseSql = baseSql.substring(0, lastParenthesis) + "," + constraints + ")";
    }
    String CREATE_SQL = tableName != null ? String.format(baseSql, tableName) : baseSql;
    Statement statement = connection.createStatement();
    try {
        statement.execute(CREATE_SQL);
    } finally {
        DbUtils.close(statement);
    }
}

From source file:com.nextep.designer.sqlgen.db2.impl.DB2DatabaseConnector.java

@Override
public void doPostConnectionSettings(IConnection conn, Connection sqlConn) throws SQLException {
    final String schema = conn.getSchema();
    /*//from   w  w w . jav  a  2  s .  c o m
     * If schema is set to a non-empty value, we set the first value of the CURRENT PATH with
     * the specified schema. We don't need to set the CURRENT SCHEMA variable as it is already
     * set with the connection properties.
     */
    if (schema != null && !"".equals(schema.trim())) { //$NON-NLS-1$
        Statement stmt = null;
        try {
            stmt = sqlConn.createStatement();
            stmt.execute("SET CURRENT PATH " + schema + ", CURRENT PATH"); //$NON-NLS-1$ //$NON-NLS-2$
        } catch (SQLException sqle) {
            LOGGER.error("Unable to set the DB2 current path: " + sqle.getMessage(), sqle);
            throw sqle;
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }
    }
}

From source file:com.mtgi.analytics.sql.BehaviorTrackingDataSourceTest.java

@Before
public void initTestTable() throws SQLException {
    sessionContext.setContextUserId("dbUser");
    sessionContext.setContextSessionId("ABCDEF123");
    stmt.execute("create table TEST_TRACKING (" + "   ID         NUMERIC(8)       PRIMARY KEY,"
            + "   NAME      VARCHAR(16)      NOT NULL," + "   DESCRIPTION   VARCHAR(32)    NULL" + ")");

    //because we've put behavior tracking at the DataSource level, all of our
    //test setup will have generated a bunch of behavior tracking events.
    //so we extract an untracked connection
    //and delete all of those events before the test starts.  it's much easier
    //to validate the data this way.
    manager.flush();/*ww  w.j  a  v  a  2  s.c  o  m*/
    Statement cleanup = ((ConnectionProxy) conn).getTargetConnection().createStatement();
    cleanup.execute("delete from BEHAVIOR_TRACKING_EVENT; " + "drop sequence SEQ_BEHAVIOR_TRACKING_EVENT; "
            + "create sequence SEQ_BEHAVIOR_TRACKING_EVENT; ");
    cleanup.close();
}

From source file:com.splicemachine.test_tools.TableCreator.java

private void createIndexes() throws SQLException {
    for (String indexSql : indexSqlList) {
        String INDEX_SQL = tableName == null ? indexSql : String.format(indexSql, tableName);
        Statement statement = connection.createStatement();
        try {//from w  w w. java 2s . c o m
            statement.execute(INDEX_SQL);
        } finally {
            DbUtils.close(statement);
        }
    }
}

From source file:be.fedict.eid.integration.setup.db.SetupDatabase.java

@BeforeSuite
@Parameters("context")
public void setupDatabase(String context) throws ClassNotFoundException, SQLException, IOException {
    try {//  www .  j ava  2 s  .com
        // Setup the database
        loadJdbcDriver();

        // Get a connection
        Connection connection = openConnection();

        // Execute the update
        try {
            Statement statement = connection.createStatement();

            try {
                String sql = readSql(context);
                statement.execute(sql);
            } finally {
                statement.close();
            }

        } finally {
            connection.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
        throw e;
    }
}