List of usage examples for java.sql Statement getUpdateCount
int getUpdateCount() throws SQLException;
ResultSet
object or there are no more results, -1 is returned. From source file:org.apache.ibatis.executor.resultset.FastResultSetHandler.java
protected ResultSet getNextResultSet(Statement stmt) throws SQLException { // Making this method tolerant of bad JDBC drivers try {// w w w .j av a 2 s . c o m if (stmt.getConnection().getMetaData().supportsMultipleResultSets()) { // Crazy Standard JDBC way of determining if there are more // results if (!((!stmt.getMoreResults()) && (stmt.getUpdateCount() == -1))) { return stmt.getResultSet(); } } } catch (Exception e) { // Intentionally ignored. } return null; }
From source file:org.apache.jackrabbit.core.fs.db.DatabaseFileSystem.java
/** * {@inheritDoc}//from w w w . jav a2s . co m */ public void deleteFile(String filePath) throws FileSystemException { if (!initialized) { throw new IllegalStateException("not initialized"); } FileSystemPathUtil.checkFormat(filePath); String parentDir = FileSystemPathUtil.getParentDir(filePath); String name = FileSystemPathUtil.getName(filePath); int count = 0; synchronized (deleteFileSQL) { try { Statement stmt = executeStmt(deleteFileSQL, new Object[] { parentDir, name }); count = stmt.getUpdateCount(); } catch (SQLException e) { String msg = "failed to delete file: " + filePath; log.error(msg, e); throw new FileSystemException(msg, e); } } if (count == 0) { throw new FileSystemException("no such file: " + filePath); } }
From source file:org.apache.jackrabbit.core.fs.db.DatabaseFileSystem.java
/** * {@inheritDoc}//from w w w. ja va2 s . co m */ public void deleteFolder(String folderPath) throws FileSystemException { if (!initialized) { throw new IllegalStateException("not initialized"); } FileSystemPathUtil.checkFormat(folderPath); if (folderPath.equals(FileSystem.SEPARATOR)) { throw new FileSystemException("cannot delete root"); } String parentDir = FileSystemPathUtil.getParentDir(folderPath); String name = FileSystemPathUtil.getName(folderPath); int count = 0; synchronized (deleteFolderSQL) { try { Statement stmt = executeStmt(deleteFolderSQL, new Object[] { parentDir, name, folderPath, folderPath + FileSystem.SEPARATOR + "%" }); count = stmt.getUpdateCount(); } catch (SQLException e) { String msg = "failed to delete folder: " + folderPath; log.error(msg, e); throw new FileSystemException(msg, e); } } if (count == 0) { throw new FileSystemException("no such folder: " + folderPath); } }
From source file:org.apache.jackrabbit.core.fs.db.DatabaseFileSystem.java
/** * {@inheritDoc}// w w w . j a v a2s. c o m */ public void touch(String filePath) throws FileSystemException { if (!initialized) { throw new IllegalStateException("not initialized"); } FileSystemPathUtil.checkFormat(filePath); String parentDir = FileSystemPathUtil.getParentDir(filePath); String name = FileSystemPathUtil.getName(filePath); int count = 0; synchronized (updateLastModifiedSQL) { try { Statement stmt = executeStmt(updateLastModifiedSQL, new Object[] { new Long(System.currentTimeMillis()), parentDir, name }); count = stmt.getUpdateCount(); } catch (SQLException e) { String msg = "failed to touch file: " + filePath; log.error(msg, e); throw new FileSystemException(msg, e); } } if (count == 0) { throw new FileSystemException("no such file: " + filePath); } }
From source file:org.apache.jackrabbit.core.fs.db.DatabaseFileSystem.java
/** * Copies the given file entry to the given destination path. The parent * folder of the destination path will be created if it doesn't exist * already. If the destination path refers to an existing file, the file * will be overwritten.// w ww . j a v a2 s . co m * * @param srcPath file to be copied * @param destPath destination path to which the file is to be copied * @throws FileSystemException if an error occurs */ protected void copyFile(String srcPath, String destPath) throws FileSystemException { final String srcParentDir = FileSystemPathUtil.getParentDir(srcPath); final String srcName = FileSystemPathUtil.getName(srcPath); final String destParentDir = FileSystemPathUtil.getParentDir(destPath); final String destName = FileSystemPathUtil.getName(destPath); if (!exists(destParentDir)) { createDeepFolder(destParentDir); } if (isFile(destPath)) { deleteFile(destPath); } int count = 0; synchronized (copyFileSQL) { try { Statement stmt = executeStmt(copyFileSQL, new Object[] { destParentDir, destName, srcParentDir, srcName }); count = stmt.getUpdateCount(); } catch (SQLException e) { String msg = "failed to copy file from " + srcPath + " to " + destPath; log.error(msg, e); throw new FileSystemException(msg, e); } } if (count == 0) { throw new FileSystemException("no such file: " + srcPath); } }
From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java
/** * Execute the test element./*w w w .j ava 2 s . c o m*/ * * @param conn a {@link SampleResult} in case the test should sample; <code>null</code> if only execution is requested * @return the result of the execute command * @throws SQLException if a database error occurs * @throws UnsupportedEncodingException when the result can not be converted to the required charset * @throws IOException when I/O error occurs * @throws UnsupportedOperationException if the user provided incorrect query type */ protected byte[] execute(Connection conn) throws SQLException, UnsupportedEncodingException, IOException, UnsupportedOperationException { log.debug("executing jdbc"); Statement stmt = null; try { // Based on query return value, get results String _queryType = getQueryType(); if (SELECT.equals(_queryType)) { stmt = conn.createStatement(); stmt.setQueryTimeout(getIntegerQueryTimeout()); ResultSet rs = null; try { rs = stmt.executeQuery(getQuery()); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } else if (CALLABLE.equals(_queryType)) { CallableStatement cstmt = getCallableStatement(conn); int[] out = setArguments(cstmt); // A CallableStatement can return more than 1 ResultSets // plus a number of update counts. boolean hasResultSet = cstmt.execute(); String sb = resultSetsToString(cstmt, hasResultSet, out); return sb.getBytes(ENCODING); } else if (UPDATE.equals(_queryType)) { stmt = conn.createStatement(); stmt.setQueryTimeout(getIntegerQueryTimeout()); stmt.executeUpdate(getQuery()); int updateCount = stmt.getUpdateCount(); String results = updateCount + " updates"; return results.getBytes(ENCODING); } else if (PREPARED_SELECT.equals(_queryType)) { PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); ResultSet rs = null; try { rs = pstmt.executeQuery(); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } else if (PREPARED_UPDATE.equals(_queryType)) { PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); pstmt.executeUpdate(); String sb = resultSetsToString(pstmt, false, null); return sb.getBytes(ENCODING); } else if (ROLLBACK.equals(_queryType)) { conn.rollback(); return ROLLBACK.getBytes(ENCODING); } else if (COMMIT.equals(_queryType)) { conn.commit(); return COMMIT.getBytes(ENCODING); } else if (AUTOCOMMIT_FALSE.equals(_queryType)) { conn.setAutoCommit(false); return AUTOCOMMIT_FALSE.getBytes(ENCODING); } else if (AUTOCOMMIT_TRUE.equals(_queryType)) { conn.setAutoCommit(true); return AUTOCOMMIT_TRUE.getBytes(ENCODING); } else { // User provided incorrect query type throw new UnsupportedOperationException("Unexpected query type: " + _queryType); } } finally { close(stmt); } }
From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCwoTimeOutTestElement.java
/** * Execute the test element./*from w w w . j a v a 2s . com*/ * * @param conn a {@link SampleResult} in case the test should sample; <code>null</code> if only execution is requested * @throws UnsupportedOperationException if the user provided incorrect query type */ @Override protected byte[] execute(final Connection conn) throws SQLException, UnsupportedEncodingException, IOException, UnsupportedOperationException { log.debug("executing jdbc"); Statement stmt = null; try { // Based on query return value, get results final String _queryType = getQueryType(); if (SELECT.equals(_queryType)) { stmt = conn.createStatement(); //stmt.setQueryTimeout(getIntegerQueryTimeout()); ResultSet rs = null; try { final String query = getQuery(); System.out.println(query); rs = stmt.executeQuery(query); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } else if (CALLABLE.equals(_queryType)) { final CallableStatement cstmt = getCallableStatement(conn); final int out[] = setArguments(cstmt); // A CallableStatement can return more than 1 ResultSets // plus a number of update counts. final boolean hasResultSet = cstmt.execute(); final String sb = resultSetsToString(cstmt, hasResultSet, out); return sb.getBytes(ENCODING); } else if (UPDATE.equals(_queryType)) { stmt = conn.createStatement(); stmt.setQueryTimeout(getIntegerQueryTimeout()); stmt.executeUpdate(getQuery()); final int updateCount = stmt.getUpdateCount(); final String results = updateCount + " updates"; return results.getBytes(ENCODING); } else if (PREPARED_SELECT.equals(_queryType)) { final PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); System.out.println(pstmt); ResultSet rs = null; try { rs = pstmt.executeQuery(); return getStringFromResultSet(rs).getBytes(ENCODING); } finally { close(rs); } } else if (PREPARED_UPDATE.equals(_queryType)) { final PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); pstmt.executeUpdate(); final String sb = resultSetsToString(pstmt, false, null); return sb.getBytes(ENCODING); } else if (ROLLBACK.equals(_queryType)) { conn.rollback(); return ROLLBACK.getBytes(ENCODING); } else if (COMMIT.equals(_queryType)) { conn.commit(); return COMMIT.getBytes(ENCODING); } else if (AUTOCOMMIT_FALSE.equals(_queryType)) { conn.setAutoCommit(false); return AUTOCOMMIT_FALSE.getBytes(ENCODING); } else if (AUTOCOMMIT_TRUE.equals(_queryType)) { conn.setAutoCommit(true); return AUTOCOMMIT_TRUE.getBytes(ENCODING); } else { // User provided incorrect query type throw new UnsupportedOperationException("Unexpected query type: " + _queryType); } } finally { close(stmt); } }
From source file:org.apache.jmeter.protocol.jdbc.sampler.JDBCSampler.java
public SampleResult sample(Entry e) { log.debug("sampling jdbc"); SampleResult res = new SampleResult(); res.setSampleLabel(getName());/*from www .ja va2s. c o m*/ res.setSamplerData(toString()); res.setDataType(SampleResult.TEXT); res.setContentType("text/plain"); // $NON-NLS-1$ res.setDataEncoding(ENCODING); // Assume we will be successful res.setSuccessful(true); res.setResponseMessageOK(); res.setResponseCodeOK(); res.sampleStart(); Connection conn = null; Statement stmt = null; try { try { conn = DataSourceElement.getConnection(getDataSource()); } finally { res.latencyEnd(); // use latency to measure connection time } res.setResponseHeaders(conn.toString()); // Based on query return value, get results String _queryType = getQueryType(); if (SELECT.equals(_queryType)) { stmt = conn.createStatement(); ResultSet rs = null; try { rs = stmt.executeQuery(getQuery()); res.setResponseData(getStringFromResultSet(rs).getBytes(ENCODING)); } finally { close(rs); } } else if (CALLABLE.equals(_queryType)) { CallableStatement cstmt = getCallableStatement(conn); int out[] = setArguments(cstmt); // A CallableStatement can return more than 1 ResultSets // plus a number of update counts. boolean hasResultSet = cstmt.execute(); String sb = resultSetsToString(cstmt, hasResultSet, out); res.setResponseData(sb.getBytes(ENCODING)); } else if (UPDATE.equals(_queryType)) { stmt = conn.createStatement(); stmt.executeUpdate(getQuery()); int updateCount = stmt.getUpdateCount(); String results = updateCount + " updates"; res.setResponseData(results.getBytes(ENCODING)); } else if (PREPARED_SELECT.equals(_queryType)) { PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); pstmt.executeQuery(); String sb = resultSetsToString(pstmt, true, null); res.setResponseData(sb.getBytes(ENCODING)); } else if (PREPARED_UPDATE.equals(_queryType)) { PreparedStatement pstmt = getPreparedStatement(conn); setArguments(pstmt); pstmt.executeUpdate(); String sb = resultSetsToString(pstmt, false, null); res.setResponseData(sb.getBytes(ENCODING)); } else if (ROLLBACK.equals(_queryType)) { conn.rollback(); res.setResponseData(ROLLBACK.getBytes(ENCODING)); } else if (COMMIT.equals(_queryType)) { conn.commit(); res.setResponseData(COMMIT.getBytes(ENCODING)); } else if (AUTOCOMMIT_FALSE.equals(_queryType)) { conn.setAutoCommit(false); res.setResponseData(AUTOCOMMIT_FALSE.getBytes(ENCODING)); } else if (AUTOCOMMIT_TRUE.equals(_queryType)) { conn.setAutoCommit(true); res.setResponseData(AUTOCOMMIT_TRUE.getBytes(ENCODING)); } else { // User provided incorrect query type String results = "Unexpected query type: " + _queryType; res.setResponseMessage(results); res.setSuccessful(false); } } catch (SQLException ex) { final String errCode = Integer.toString(ex.getErrorCode()); res.setResponseMessage(ex.toString()); res.setResponseCode(ex.getSQLState() + " " + errCode); res.setSuccessful(false); } catch (UnsupportedEncodingException ex) { res.setResponseMessage(ex.toString()); res.setResponseCode("000"); // TODO - is this correct? res.setSuccessful(false); } catch (IOException ex) { res.setResponseMessage(ex.toString()); res.setResponseCode("000"); // TODO - is this correct? res.setSuccessful(false); } finally { close(stmt); close(conn); } // TODO: process warnings? Set Code and Message to success? res.sampleEnd(); return res; }
From source file:org.apache.zeppelin.hopshive.HopsHiveInterpreter.java
private InterpreterResult executeSql(String propertyKey, String sql, InterpreterContext interpreterContext) { Connection connection;/*from w ww . j av a2s . c om*/ Statement statement; ResultSet resultSet = null; String paragraphId = interpreterContext.getParagraphId(); String user = interpreterContext.getAuthenticationInfo().getUser(); boolean splitQuery = false; String splitQueryProperty = getProperty(String.format("%s.%s", propertyKey, SPLIT_QURIES_KEY)); if (StringUtils.isNotBlank(splitQueryProperty) && splitQueryProperty.equalsIgnoreCase("true")) { splitQuery = true; } InterpreterResult interpreterResult = new InterpreterResult(InterpreterResult.Code.SUCCESS); try { connection = getConnection(propertyKey, interpreterContext); if (connection == null) { return new InterpreterResult(Code.ERROR, "Prefix not found."); } List<String> sqlArray; if (splitQuery) { sqlArray = splitSqlQueries(sql); } else { sqlArray = Arrays.asList(sql); } for (int i = 0; i < sqlArray.size(); i++) { String sqlToExecute = sqlArray.get(i); statement = connection.createStatement(); // fetch n+1 rows in order to indicate there's more rows available (for large selects) statement.setFetchSize(getMaxResult()); statement.setMaxRows(getMaxResult() + 1); if (statement == null) { return new InterpreterResult(Code.ERROR, "Prefix not found."); } try { getJDBCConfiguration(user).saveStatement(paragraphId, statement); boolean isResultSetAvailable = statement.execute(sqlToExecute); getJDBCConfiguration(user).setConnectionInDBDriverPoolSuccessful(propertyKey); if (isResultSetAvailable) { resultSet = statement.getResultSet(); // Regards that the command is DDL. if (isDDLCommand(statement.getUpdateCount(), resultSet.getMetaData().getColumnCount())) { interpreterResult.add(InterpreterResult.Type.TEXT, "Query executed successfully."); } else { String results = getResults(resultSet, !containsIgnoreCase(sqlToExecute, EXPLAIN_PREDICATE)); interpreterResult.add(results); if (resultSet.next()) { interpreterResult.add(ResultMessages.getExceedsLimitRowsMessage(getMaxResult(), String.format("%s.%s", COMMON_KEY, MAX_LINE_KEY))); } } } else { // Response contains either an update count or there are no results. int updateCount = statement.getUpdateCount(); interpreterResult.add(InterpreterResult.Type.TEXT, "Query executed successfully. Affected rows : " + updateCount); } } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { /*ignored*/ } } if (statement != null) { try { statement.close(); } catch (SQLException e) { /*ignored*/ } } } } //In case user ran an insert/update/upsert statement if (connection != null) { try { if (!connection.getAutoCommit()) { connection.commit(); } } catch (SQLException e) { /*ignored*/ } } getJDBCConfiguration(user).removeStatement(paragraphId); } catch (Throwable e) { logger.error("Cannot run " + sql, e); String errorMsg = Throwables.getStackTraceAsString(e); interpreterResult.add(errorMsg); return new InterpreterResult(Code.ERROR, interpreterResult.message()); } return interpreterResult; }
From source file:org.apache.zeppelin.jdbc.JDBCInterpreter.java
private InterpreterResult executeSql(String propertyKey, String sql, InterpreterContext interpreterContext) { Connection connection;// w w w .j av a 2 s. c om Statement statement; ResultSet resultSet = null; String paragraphId = interpreterContext.getParagraphId(); String user = interpreterContext.getAuthenticationInfo().getUser(); InterpreterResult interpreterResult = new InterpreterResult(InterpreterResult.Code.SUCCESS); try { connection = getConnection(propertyKey, interpreterContext); if (connection == null) { return new InterpreterResult(Code.ERROR, "Prefix not found."); } ArrayList<String> multipleSqlArray = splitSqlQueries(sql); for (int i = 0; i < multipleSqlArray.size(); i++) { String sqlToExecute = multipleSqlArray.get(i); statement = connection.createStatement(); if (statement == null) { return new InterpreterResult(Code.ERROR, "Prefix not found."); } try { getJDBCConfiguration(user).saveStatement(paragraphId, statement); boolean isResultSetAvailable = statement.execute(sqlToExecute); getJDBCConfiguration(user).setConnectionInDBDriverPoolSuccessful(propertyKey); if (isResultSetAvailable) { resultSet = statement.getResultSet(); // Regards that the command is DDL. if (isDDLCommand(statement.getUpdateCount(), resultSet.getMetaData().getColumnCount())) { interpreterResult.add(InterpreterResult.Type.TEXT, "Query executed successfully."); } else { interpreterResult.add( getResults(resultSet, !containsIgnoreCase(sqlToExecute, EXPLAIN_PREDICATE))); } } else { // Response contains either an update count or there are no results. int updateCount = statement.getUpdateCount(); interpreterResult.add(InterpreterResult.Type.TEXT, "Query executed successfully. Affected rows : " + updateCount); } } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { /*ignored*/ } } if (statement != null) { try { statement.close(); } catch (SQLException e) { /*ignored*/ } } } } //In case user ran an insert/update/upsert statement if (connection != null) { try { if (!connection.getAutoCommit()) { connection.commit(); } connection.close(); } catch (SQLException e) { /*ignored*/ } } getJDBCConfiguration(user).removeStatement(paragraphId); } catch (Exception e) { if (e.getCause() instanceof TTransportException && Throwables.getStackTraceAsString(e).contains("GSS") && getJDBCConfiguration(user).isConnectionInDBDriverPoolSuccessful(propertyKey)) { return reLoginFromKeytab(propertyKey, sql, interpreterContext, interpreterResult); } else { logger.error("Cannot run " + sql, e); String errorMsg = Throwables.getStackTraceAsString(e); try { closeDBPool(user, propertyKey); } catch (SQLException e1) { logger.error("Cannot close DBPool for user, propertyKey: " + user + propertyKey, e1); } interpreterResult.add(errorMsg); return new InterpreterResult(Code.ERROR, interpreterResult.message()); } } return interpreterResult; }