List of usage examples for java.sql Statement execute
boolean execute(String sql) throws SQLException;
From source file:net.riezebos.thoth.configuration.persistence.dbs.DDLExecuter.java
protected void executeSingleStmt(Connection conn, Statement stmt, String command) throws DDLException { String actual = command;/* www .j a v a 2 s . c o m*/ try { String dialect = applyDialect(command); println(dialect); actual = dialect; if (StringUtils.isNotBlank(dialect)) stmt.execute(dialect); } catch (SQLException e) { LOG.error(e.getMessage(), e); throw new DDLException("Error executing " + actual + "\n" + e.toString()); } }
From source file:it.geosolutions.geobatch.imagemosaic.MetadataPresentationOnlineTest.java
/** * Replicated from GranuleRemoverOnlineTest... put it in a Utility class? * * @throws MalformedURLException/* w ww . java 2s .c o m*/ * @throws ClassNotFoundException * @throws SQLException */ protected void removeStore() throws MalformedURLException, ClassNotFoundException, SQLException { // remove existing store from GeoServer GeoServerRESTReader gsReader = createGSReader(); GeoServerRESTPublisher publisher = createGSPublisher(); if (null != gsReader.getCoverageStore(WORKSPACE, STORENAME)) { LOGGER.info("Removing existing store"); publisher.removeCoverageStore(WORKSPACE, STORENAME, true); } // remove table from PG Connection connection = createPGConnection(); try { LOGGER.info("Checking if PG table '" + STORENAME + "' exists"); Statement st = connection.createStatement(); st.execute("SELECT count(*) FROM " + getFixture().getProperty("pg_schema") + ".\"" + STORENAME + "\""); st.close(); // previous select did not issue an exception, so the table does exist. try { LOGGER.info("Removing PG table '" + STORENAME + "'"); st = connection.createStatement(); st.executeUpdate("DROP TABLE " + getFixture().getProperty("pg_schema") + ".\"" + STORENAME + "\""); st.close(); } catch (SQLException ex) { LOGGER.warn("Error while dropping table"); } } catch (Exception e) { LOGGER.info("The store " + STORENAME + " probably does not exist: " + e.getMessage()); } finally { connection.close(); } }
From source file:com.cloudera.recordbreaker.analyzer.DataQuery.java
public DataQuery() throws SQLException { try {/*from w ww . java 2 s .com*/ this.conf = new Configuration(); Class.forName(hiveDriverName); Class.forName(impalaDriverName); this.hiveConnectString = conf.get("hive.connectstring", "jdbc:hive2://localhost:10000/default"); this.impalaConnectString = conf.get("impala.connectstring", "jdbc:hive2://localhost:21050/;auth=noSasl"); LOG.info("Hive connect string: " + hiveConnectString); LOG.info("Impala connect string: " + impalaConnectString); this.tableCache = new HiveTableCache(); try { this.hiveCon = DriverManager.getConnection(hiveConnectString, "cloudera", "cloudera"); } catch (Exception ex) { ex.printStackTrace(); } this.impalaCon = DriverManager.getConnection(impalaConnectString, "cloudera", "cloudera"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } // Force impala to refresh metadata if (impalaCon != null) { Statement stmt = impalaCon.createStatement(); try { try { LOG.info("Rebuilding Impala metadata..."); stmt.execute("INVALIDATE METADATA"); } catch (Exception iex) { LOG.info("Impala metadata rebuild failed: " + iex.toString()); } } finally { stmt.close(); } } // Misc data structures this.tables = new HashMap<Path, String>(); this.isLoaded = new HashSet<Path>(); }
From source file:de.xwic.sandbox.server.installer.impl.SQLServerDatabaseHandler.java
public boolean dropColumn(String fromTable, String columnName) { String sql = "IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS " + " WHERE TABLE_NAME = '" + fromTable + "' AND COLUMN_NAME = '" + columnName + "'" + " ) ALTER TABLE " + fromTable + " DROP COLUMN " + columnName;//from w w w .j av a 2 s .c o m try { Statement stmt = connection.createStatement(); try { stmt.execute(sql); } finally { stmt.close(); } return true; } catch (Exception e) { // the update process should not be aborted when this happens, so // its just a warning log.warn("Error dropping in table '" + fromTable + "', column '" + columnName + "'"); return false; } }
From source file:com.mirth.connect.server.userutil.DatabaseConnection.java
/** * Executes an INSERT/UPDATE on the database and returns the row count. * //from w ww. j a v a 2s.c o m * @param expression * The statement to be executed. * @return A count of the number of updated rows. * @throws SQLException */ public int executeUpdate(String expression) throws SQLException { Statement statement = null; try { statement = connection.createStatement(); logger.debug("executing update:\n" + expression); if (statement.execute(expression)) { return -1; } else { return statement.getUpdateCount(); } } catch (SQLException e) { throw e; } finally { DbUtils.closeQuietly(statement); } }
From source file:org.gsoft.admin.ScriptRunner.java
/** * Runs an SQL script (read in using the Reader parameter) using the * connection passed in//from w w w. j a v a 2 s .c o m * * @param conn * - the connection to use for the script * @param reader * - the source of the script * @throws SQLException * if any SQL errors occur * @throws IOException * if there is an error reading from the Reader */ private void runScript(Connection conn, Reader reader) throws IOException, SQLException { StringBuffer command = null; try { LineNumberReader lineReader = new LineNumberReader(reader); String line = null; while ((line = lineReader.readLine()) != null) { if (command == null) { command = new StringBuffer(); } String trimmedLine = line.trim(); if (trimmedLine.startsWith("--")) { println(trimmedLine); } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) { // Do nothing } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) { // Do nothing } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter()) || fullLineDelimiter && trimmedLine.equals(getDelimiter())) { command.append(line.substring(0, line.lastIndexOf(getDelimiter()))); command.append(" "); Statement statement = conn.createStatement(); println(command); boolean hasResults = false; if (stopOnError) { hasResults = statement.execute(command.toString()); } else { try { statement.execute(command.toString()); } catch (SQLException e) { e.fillInStackTrace(); printlnError("Error executing: " + command); printlnError(e); } } if (autoCommit && !conn.getAutoCommit()) { conn.commit(); } ResultSet rs = statement.getResultSet(); if (hasResults && rs != null) { ResultSetMetaData md = rs.getMetaData(); int cols = md.getColumnCount(); for (int i = 0; i < cols; i++) { String name = md.getColumnLabel(i); print(name + "\t"); } println(""); while (rs.next()) { for (int i = 0; i < cols; i++) { String value = rs.getString(i); print(value + "\t"); } println(""); } } command = null; try { statement.close(); } catch (Exception e) { // Ignore to workaround a bug in Jakarta DBCP } Thread.yield(); } else { command.append(line); command.append(" "); } } if (!autoCommit) { conn.commit(); } } catch (SQLException e) { e.fillInStackTrace(); printlnError("Error executing: " + command); printlnError(e); throw e; } catch (IOException e) { e.fillInStackTrace(); printlnError("Error executing: " + command); printlnError(e); throw e; } finally { conn.rollback(); flush(); } }
From source file:com.streamsets.pipeline.stage.origin.jdbc.TestJdbcSource.java
@Test public void testEmptyResultSet() throws Exception { Statement statement = connection.createStatement(); statement.execute("TRUNCATE TABLE TEST.TEST_TABLE"); JdbcSource origin = new JdbcSource(true, query, initialOffset, "P_ID", queryInterval, "FIRST_NAME", 1000, JdbcRecordType.LIST_MAP, BATCH_SIZE, CLOB_SIZE, createConfigBean(h2ConnectionString, username, password)); SourceRunner runner = new SourceRunner.Builder(JdbcDSource.class, origin).addOutputLane("lane").build(); runner.runInit();/* w w w . j ava 2s .c o m*/ try { // Check that existing rows are loaded. StageRunner.Output output = runner.runProduce(null, 1000); Map<String, List<Record>> recordMap = output.getRecords(); List<Record> parsedRecords = recordMap.get("lane"); assertEquals(0, parsedRecords.size()); assertEquals(initialOffset, output.getNewOffset()); } finally { runner.runDestroy(); } }
From source file:com.mirth.connect.server.migration.Migrator.java
protected void executeScript(String scriptFile, Map<String, Object> replacements) throws MigrationException { Statement statement = null; ResultSet resultSet = null;/* www . j a v a2s . c o m*/ try { List<String> statements = readStatements(scriptFile, replacements); connection.setAutoCommit(true); statement = connection.createStatement(); for (String statementString : statements) { statement.execute(statementString); } } catch (Exception e) { throw new MigrationException("Failed to execute script: " + scriptFile, e); } finally { DbUtils.closeQuietly(statement); DbUtils.closeQuietly(resultSet); } }
From source file:com.yahoo.ycsb.db.JdbcDBClient.java
@Override public Status scan(String tableName, String startKey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { try {/*from w ww . ja va 2s. co m*/ Connection connection = getShardConnectionByKey(startKey); if (isCitus) { Statement stmt = connection.createStatement(); stmt.execute("SET citusdb.task_executor_type TO 'real-time'"); } StringBuilder select = new StringBuilder("SELECT * FROM "); select.append(tableName); select.append(" WHERE "); select.append(PRIMARY_KEY); select.append(" >= "); select.append("'"); select.append(StringEscapeUtils.escapeSql(startKey)); select.append("'"); select.append(" ORDER BY "); select.append(PRIMARY_KEY); select.append(" LIMIT "); select.append(recordcount); Statement scanStatement = connection.createStatement(); ResultSet resultSet = scanStatement.executeQuery(select.toString()); for (int i = 0; i < recordcount && resultSet.next(); i++) { if (result != null && fields != null) { HashMap<String, ByteIterator> values = new HashMap<String, ByteIterator>(); for (String field : fields) { String value = resultSet.getString(field); values.put(field, new StringByteIterator(value)); } result.add(values); } } resultSet.close(); if (isCitus) { Statement stmt = connection.createStatement(); stmt.execute("SET citusdb.task_executor_type TO 'router'"); } return Status.OK; } catch (SQLException e) { System.err.println("Error in processing scan of table: " + tableName + e); return Status.ERROR; } }
From source file:io.confluent.connect.jdbc.EmbeddedDerby.java
/** * Shorthand for creating a table/*w w w. j a va 2 s.com*/ * @param name name of the table * @param fields list of field names followed by specs specifications, e.g. "user-id", * "INT NOT NULL", "username", "VARCHAR(20)". May include other settings like * "PRIMARY KEY user_id" */ public void createTable(String name, String... fields) throws SQLException { if (fields.length == 0) { throw new IllegalArgumentException("Must specify at least one column when creating a table"); } if (fields.length % 2 != 0) { throw new IllegalArgumentException("Must specify files in pairs of name followed by " + "column spec"); } StringBuilder statement = new StringBuilder(); statement.append("CREATE TABLE "); statement.append(quoteCaseSensitive(name)); statement.append(" ("); for (int i = 0; i < fields.length; i += 2) { if (i > 0) { statement.append(", "); } statement.append(quoteCaseSensitive(fields[i])); statement.append(" "); statement.append(fields[i + 1]); } statement.append(")"); Statement stmt = conn.createStatement(); String statementStr = statement.toString(); log.debug("Creating table {} in {} with statement {}", name, this.name, statementStr); stmt.execute(statementStr); }