List of usage examples for java.sql Statement execute
boolean execute(String sql) throws SQLException;
From source file:jp.primecloud.auto.tool.management.db.SQLExecuter.java
public void execute(String sql) throws SQLException, Exception { Connection con = null;/*from w w w .j a v a2s .c o m*/ Statement stmt = null; ResultSet rs = null; String logSQL = ""; // ?? logSQL = passwordMask(sql); log.info("[" + logSQL + "] ???"); try { con = dbConnector.getConnection(); stmt = con.createStatement(); stmt.execute(sql); log.info("[" + logSQL + "] ????"); } catch (SQLException e) { log.error(passwordMask(e.getMessage()), e); throw new SQLException(e); } catch (Exception e) { log.error(passwordMask(e.getMessage()), e); throw new Exception(e); } finally { try { dbConnector.closeConnection(con, stmt, rs); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.thinkbiganalytics.nifi.v2.thrift.RefreshableDataSource.java
/** * @param statement statement handle to use for execution * @param validationQuery query to use to check the connection * @param timeout time, in seconds, to wait for the query to complete * @return true if query had to be timed out, false otherwise. */// w w w . j av a2 s . c o m private synchronized boolean validateQueryWithTimeout(final Statement statement, final String validationQuery, int timeout) throws SQLException { log.info("perform validation query in RefreshableDatasource.executeWithTimeout()"); final Stopwatch timer = Stopwatch.createStarted(); try { executor.submit(() -> statement.execute(validationQuery)).get(timeout, TimeUnit.SECONDS); log.info("validation query returned from RefreshableDatasource.executeWithTimeout() in {}", timer.stop()); return true; } catch (final InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Unlikely scenario that query thread was interrupted. Application going down?", e); throw new SQLException(e); } catch (final TimeoutException e) { return false; } catch (final Exception e) { Throwables.propagateIfInstanceOf(e.getCause(), SQLException.class); throw Throwables.propagate(e.getCause()); } }
From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java
/** * Verify that even with an empty ResultSet; the resultset meta-data can still * be queried. Previously, this was <i>Issue 75</i>. *///from ww w. jav a 2 s.c o m @Test public void testEmptyResultSet() throws Exception { Statement stmt = con.createStatement(); String truncate = "TRUNCATE regressiontest;"; stmt.execute(truncate); String select = "select ivalue from " + TABLE; ResultSet result = stmt.executeQuery(select); assertFalse("Make sure we have no rows", result.next()); ResultSetMetaData rsmd = result.getMetaData(); assertTrue("Make sure we do get a result", rsmd.getColumnDisplaySize(1) != 0); assertNotNull("Make sure we do get a label", rsmd.getColumnLabel(1)); System.out.println( "Found a column in ResultsetMetaData even when there are no rows: " + rsmd.getColumnLabel(1)); stmt.close(); }
From source file:com.uber.hoodie.hive.HoodieHiveClient.java
/** * Execute a update in hive metastore with this SQL * * @param s SQL to execute/*from www . ja v a2 s. co m*/ */ void updateHiveSQL(String s) { Statement stmt = null; try { stmt = connection.createStatement(); LOG.info("Executing SQL " + s); stmt.execute(s); } catch (SQLException e) { throw new HoodieHiveSyncException("Failed in executing SQL " + s, e); } finally { closeQuietly(null, stmt); } }
From source file:com.splicemachine.derby.test.framework.SpliceIndexWatcher.java
@Override public void starting(Description description) { LOG.trace("Starting"); Connection connection = null; PreparedStatement statement = null; Statement statement2 = null; ResultSet rs = null;//w ww .j a va 2s . c o m try { connection = SpliceNetConnection.getConnection(); statement = connection.prepareStatement(SELECT_SPECIFIC_INDEX); statement.setString(1, indexSchemaName); statement.setString(2, indexName); rs = statement.executeQuery(); if (rs.next()) { executeDrop(connection, indexSchemaName, indexName); } connection.commit(); statement2 = connection.createStatement(); statement2.execute(String.format("%s index %s.%s on %s.%s %s", create, indexSchemaName, indexName, tableSchemaName, tableName, createString)); connection.commit(); } catch (Exception e) { LOG.error("Create index statement is invalid "); throw new RuntimeException(e); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(statement); DbUtils.closeQuietly(statement2); DbUtils.commitAndCloseQuietly(connection); } super.starting(description); }
From source file:org.jspringbot.keyword.db.DbHelper.java
public void useSchema(final String param) { schema = param;/*from w w w. j a va2s . c om*/ session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement stmt = connection.createStatement(); try { LOG.createAppender().appendBold("Use Schema:").appendProperty("Schema", param).log(); stmt.execute(String.format(useSchemaSyntax, schema)); } finally { stmt.close(); } } }); }
From source file:edu.ncsa.sstde.indexing.postgis.PostgisIndexerSettings.java
private void createTables(Connection conn) throws IOException, SQLException { Collection<String> varNames = this.getIndexGraph().getVarNames(); String createClause = "create table " + getTableName() + "("; StringBuffer indexClause = new StringBuffer(); // StringBuffer uniqueClause = new StringBuffer("ALTER TABLE " // + getTableName() // + " ADD CONSTRAINT unique_index_constraint_" + getTableName() + " UNIQUE("); //add the first column as the primary, which is a 32 characters MD5 code to indicate the unique graph createClause += OID + " character(32) NOT NULL,CONSTRAINT " + getTableName() + "_pk PRIMARY KEY (" + OID + "),"; for (String varname : varNames) { String sqlType = getVarType(varname); createClause += varname + " " + sqlType + " NOT NULL,"; String indexName = "index_" + getTableName() + "_" + varname; String indexType = sqlType.equals("geometry") ? "gist" : "btree"; indexClause.append("CREATE INDEX " + indexName + " ON " + getTableName() + " USING " + indexType + " (" + varname + ");"); // uniqueClause.append(varname).append(','); }// w ww . j av a2 s . c o m createClause = createClause.substring(0, createClause.length() - 1) + ") WITH (OIDS=FALSE);"; // uniqueClause.deleteCharAt(uniqueClause.length()-1).append(")"); Statement stat = conn.createStatement(); try { stat.execute(createClause + indexClause.toString()); // for (Entry<String, String> childTable: // getPartitionCheckConstraints().entrySet()) { // String tableName = getTableName(childTable.getKey()); // stat.execute(replaceVars(sqlChild, getBaseTable(), tableName, // childTable.getValue())); // } } finally { stat.close(); } }
From source file:au.edu.jcu.fascinator.plugin.harvester.directory.DerbyCache.java
/** * Create the given table in the database. * //from w w w . j av a 2s . c o m * @param table The table to create * @throws SQLException if there was an error during creation, or an unknown * table was specified. */ private void createTable(String table) throws SQLException { if (table.equals(BASIC_TABLE)) { Statement sql = connection().createStatement(); sql.execute("CREATE TABLE " + BASIC_TABLE + "(oid VARCHAR(255) NOT NULL, " + "cacheId VARCHAR(255) NOT NULL, " + "lastModified TIMESTAMP NOT NULL, " + "changeFlag SMALLINT NOT NULL, " + "PRIMARY KEY (oid, cacheId))"); close(sql); return; } if (table.equals(HASH_TABLE)) { Statement sql = connection().createStatement(); sql.execute("CREATE TABLE " + HASH_TABLE + "(oid VARCHAR(255) NOT NULL, " + "cacheId VARCHAR(255) NOT NULL, " + "hash VARCHAR(50) NOT NULL, " + "changeFlag SMALLINT NOT NULL, " + "PRIMARY KEY (oid, cacheId))"); close(sql); return; } throw new SQLException("Unknown table '" + table + "' requested!"); }
From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java
/** * Verify that the driver navigates a resultset according to the JDBC rules. * In all cases, the resultset should be pointing to the first record, which can * be read without invoking {@code next()}. * @throws Exception Fatal error.//from ww w.j a v a 2s . c om */ @Test public void testResultSetNavigation() throws Exception { Statement statement = con.createStatement(); String truncate = "TRUNCATE regressiontest;"; statement.execute(truncate); String insert1 = "INSERT INTO regressiontest (keyname,bValue,iValue) VALUES( 'key0',true, 2000);"; statement.executeUpdate(insert1); String insert2 = "INSERT INTO regressiontest (keyname,bValue) VALUES( 'key1',false);"; statement.executeUpdate(insert2); String select = "SELECT * from regressiontest;"; ResultSet result = statement.executeQuery(select); ResultSetMetaData metadata = result.getMetaData(); int colCount = metadata.getColumnCount(); System.out.println("Before doing a next()"); System.out.printf("(%d) ", result.getRow()); for (int i = 1; i <= colCount; i++) { System.out.print(showColumn(i, result) + " "); } System.out.println(); System.out.println("Fetching each row with a next()"); while (result.next()) { metadata = result.getMetaData(); colCount = metadata.getColumnCount(); System.out.printf("(%d) ", result.getRow()); for (int i = 1; i <= colCount; i++) { System.out.print(showColumn(i, result) + " "); } System.out.println(); } }
From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java
public void testPrepareExecute() throws SQLException { Statement stat = conn.createStatement(); stat.execute("prepare test(int, int) as select ?1*?2"); ResultSet rs = stat.executeQuery("execute test(3, 2)"); rs.next();/*from w w w . ja v a 2s . c o m*/ assertEquals(6, rs.getInt(1)); stat.execute("deallocate test"); }