Java Code Examples for com.j256.ormlite.misc.IOUtils#closeThrowSqlException()

The following examples show how to use com.j256.ormlite.misc.IOUtils#closeThrowSqlException() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return a results object associated with an internal iterator that returns String[] results.
 */
public GenericRawResults<String[]> queryRaw(ConnectionSource connectionSource, String query, String[] arguments,
		ObjectCache objectCache) throws SQLException {
	logger.debug("executing raw query for: {}", query);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("query arguments: {}", (Object) arguments);
	}
	DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
	CompiledStatement compiledStatement = null;
	try {
		compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		assignStatementArguments(compiledStatement, arguments);
		GenericRawResults<String[]> rawResults = new RawResultsImpl<String[]>(connectionSource, connection, query,
				String[].class, compiledStatement, this, objectCache);
		compiledStatement = null;
		connection = null;
		return rawResults;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example 2
Source File: SelectIterator.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Returns whether or not there are any remaining objects in the table. Can be called before next().
 * 
 * @throws SQLException
 *             If there was a problem getting more results via SQL.
 */
public boolean hasNextThrow() throws SQLException {
	if (closed) {
		return false;
	}
	if (alreadyMoved) {
		// we do this so multiple hasNext() calls can be made, result would be true or closed is true
		return true;
	}
	boolean result;
	if (first) {
		first = false;
		result = results.first();
	} else {
		result = results.next();
	}
	if (!result) {
		IOUtils.closeThrowSqlException(this, "iterator");
	}
	alreadyMoved = true;
	return result;
}
 
Example 3
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return true if it worked else false.
 */
public int executeRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException {
	logger.debug("running raw execute statement: {}", statement);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("execute arguments: {}", (Object) arguments);
	}
	CompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.EXECUTE,
			noFieldTypes, DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
	try {
		assignStatementArguments(compiledStatement, arguments);
		return compiledStatement.runExecute();
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example 4
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return the number of rows affected.
 */
public int updateRaw(DatabaseConnection connection, String statement, String[] arguments) throws SQLException {
	logger.debug("running raw update statement: {}", statement);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("update arguments: {}", (Object) arguments);
	}
	CompiledStatement compiledStatement = connection.compileStatement(statement, StatementType.UPDATE, noFieldTypes,
			DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
	try {
		assignStatementArguments(compiledStatement, arguments);
		return compiledStatement.runUpdate();
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example 5
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return a results object associated with an internal iterator is mapped by the user's rowMapper.
 */
public <UO> GenericRawResults<UO> queryRaw(ConnectionSource connectionSource, String query,
		DatabaseResultsMapper<UO> mapper, String[] arguments, ObjectCache objectCache) throws SQLException {
	logger.debug("executing raw query for: {}", query);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("query arguments: {}", (Object) arguments);
	}
	DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
	CompiledStatement compiledStatement = null;
	try {
		compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		assignStatementArguments(compiledStatement, arguments);
		RawResultsImpl<UO> rawResults = new RawResultsImpl<UO>(connectionSource, connection, query, Object[].class,
				compiledStatement, new UserDatabaseResultsMapper<UO>(mapper), objectCache);
		compiledStatement = null;
		connection = null;
		return rawResults;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example 6
Source File: H2DatabaseConnection.java    From ormlite-core with ISC License 6 votes vote down vote up
@Override
public <T> Object queryForOne(String statement, Object[] args, FieldType[] argFieldTypes,
		GenericRowMapper<T> rowMapper, ObjectCache objectCache) throws SQLException {
	PreparedStatement stmt =
			connection.prepareStatement(statement, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
	if (args != null) {
		statementSetArgs(stmt, args, argFieldTypes);
	}
	DatabaseResults results = new H2DatabaseResults(stmt.executeQuery(), objectCache, true);
	if (!results.next()) {
		// no results at all
		IOUtils.closeThrowSqlException(results, "results");
		return null;
	}
	T first = rowMapper.mapRow(results);
	if (results.next()) {
		return MORE_THAN_ONE;
	} else {
		return first;
	}
}
 
Example 7
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return a results object associated with an internal iterator is mapped by the user's rowMapper.
 */
public <UO> GenericRawResults<UO> queryRaw(ConnectionSource connectionSource, String query, DataType[] columnTypes,
		RawRowObjectMapper<UO> rowMapper, String[] arguments, ObjectCache objectCache) throws SQLException {
	logger.debug("executing raw query for: {}", query);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("query arguments: {}", (Object) arguments);
	}
	DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
	CompiledStatement compiledStatement = null;
	try {
		compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		assignStatementArguments(compiledStatement, arguments);
		RawResultsImpl<UO> rawResults = new RawResultsImpl<UO>(connectionSource, connection, query, String[].class,
				compiledStatement, new UserRawRowObjectMapper<UO>(rowMapper, columnTypes), objectCache);
		compiledStatement = null;
		connection = null;
		return rawResults;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example 8
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return a results object associated with an internal iterator is mapped by the user's rowMapper.
 */
public <UO> GenericRawResults<UO> queryRaw(ConnectionSource connectionSource, String query,
		RawRowMapper<UO> rowMapper, String[] arguments, ObjectCache objectCache) throws SQLException {
	logger.debug("executing raw query for: {}", query);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("query arguments: {}", (Object) arguments);
	}
	DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
	CompiledStatement compiledStatement = null;
	try {
		compiledStatement = connection.compileStatement(query, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		assignStatementArguments(compiledStatement, arguments);
		RawResultsImpl<UO> rawResults = new RawResultsImpl<UO>(connectionSource, connection, query, String[].class,
				compiledStatement, new UserRawRowMapper<UO>(rowMapper, this), objectCache);
		compiledStatement = null;
		connection = null;
		return rawResults;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example 9
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Create and return an {@link SelectIterator} for the class using a prepared statement.
 */
public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource,
		PreparedStmt<T> preparedStmt, ObjectCache objectCache, int resultFlags) throws SQLException {
	DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
	CompiledStatement compiledStatement = null;
	try {
		compiledStatement = preparedStmt.compile(connection, StatementType.SELECT, resultFlags);
		SelectIterator<T, ID> iterator = new SelectIterator<T, ID>(tableInfo.getDataClass(), classDao, preparedStmt,
				connectionSource, connection, compiledStatement, preparedStmt.getStatement(), objectCache);
		connection = null;
		compiledStatement = null;
		return iterator;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
		if (connection != null) {
			connectionSource.releaseConnection(connection);
		}
	}
}
 
Example 10
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return a long from a raw query with String[] arguments.
 */
public long queryForLong(DatabaseConnection databaseConnection, String query, String[] arguments)
		throws SQLException {
	logger.debug("executing raw query for long: {}", query);
	if (arguments.length > 0) {
		// need to do the (Object) cast to force args to be a single object
		logger.trace("query arguments: {}", (Object) arguments);
	}
	CompiledStatement compiledStatement = null;
	DatabaseResults results = null;
	try {
		compiledStatement = databaseConnection.compileStatement(query, StatementType.SELECT, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		assignStatementArguments(compiledStatement, arguments);
		results = compiledStatement.runQuery(null);
		if (results.first()) {
			return results.getLong(0);
		} else {
			throw new SQLException("No result found in queryForLong: " + query);
		}
	} finally {
		IOUtils.closeThrowSqlException(results, "results");
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example 11
Source File: TableUtils.java    From ormlite-core with ISC License 6 votes vote down vote up
private static <T> int clearTable(ConnectionSource connectionSource, String schemaName, String tableName) throws SQLException {
	DatabaseType databaseType = connectionSource.getDatabaseType();
	StringBuilder sb = new StringBuilder(48);
	if (databaseType.isTruncateSupported()) {
		sb.append("TRUNCATE TABLE ");
	} else {
		sb.append("DELETE FROM ");
	}
	if (schemaName != null && schemaName.length() > 0){
		databaseType.appendEscapedEntityName(sb, schemaName);
		sb.append('.');
	}
	databaseType.appendEscapedEntityName(sb, tableName);
	String statement = sb.toString();
	logger.info("clearing table '{}' with '{}", tableName, statement);
	CompiledStatement compiledStmt = null;
	DatabaseConnection connection = connectionSource.getReadWriteConnection(tableName);
	try {
		compiledStmt = connection.compileStatement(statement, StatementType.EXECUTE, noFieldTypes,
				DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
		return compiledStmt.runExecute();
	} finally {
		IOUtils.closeThrowSqlException(compiledStmt, "compiled statement");
		connectionSource.releaseConnection(connection);
	}
}
 
Example 12
Source File: StatementExecutor.java    From ormlite-core with ISC License 6 votes vote down vote up
/**
 * Return the first object that matches the {@link PreparedStmt} or null if none.
 */
public T queryForFirst(DatabaseConnection databaseConnection, PreparedStmt<T> preparedStmt, ObjectCache objectCache)
		throws SQLException {
	CompiledStatement compiledStatement = preparedStmt.compile(databaseConnection, StatementType.SELECT);
	DatabaseResults results = null;
	try {
		compiledStatement.setMaxRows(1);
		results = compiledStatement.runQuery(objectCache);
		if (results.first()) {
			logger.debug("query-for-first of '{}' returned at least 1 result", preparedStmt.getStatement());
			return preparedStmt.mapRow(results);
		} else {
			logger.debug("query-for-first of '{}' returned 0 results", preparedStmt.getStatement());
			return null;
		}
	} finally {
		IOUtils.closeThrowSqlException(results, "results");
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example 13
Source File: MappedPreparedQueryTest.java    From ormlite-core with ISC License 6 votes vote down vote up
private void checkResults(List<LocalFoo> foos, MappedPreparedStmt<LocalFoo, Integer> preparedQuery, int expectedNum)
		throws SQLException {
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(TABLE_NAME);
	CompiledStatement stmt = null;
	try {
		stmt = preparedQuery.compile(conn, StatementType.SELECT);
		DatabaseResults results = stmt.runQuery(null);
		int fooC = 0;
		while (results.next()) {
			LocalFoo foo2 = preparedQuery.mapRow(results);
			assertEquals(foos.get(fooC).id, foo2.id);
			fooC++;
		}
		assertEquals(expectedNum, fooC);
	} finally {
		IOUtils.closeThrowSqlException(stmt, "compiled statement");
		connectionSource.releaseConnection(conn);
	}
}
 
Example 14
Source File: SchemaUtils.java    From ormlite-core with ISC License 5 votes vote down vote up
private static int doStatements(DatabaseConnection connection, String label, Collection<String> statements,
                                boolean ignoreErrors, boolean returnsNegative, boolean expectingZero) throws SQLException {
    int stmtC = 0;
    for (String statement : statements) {
        int rowC = 0;
        CompiledStatement compiledStmt = null;
        try {
            compiledStmt = connection.compileStatement(statement, StatementType.EXECUTE, noFieldTypes,
                    DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
            rowC = compiledStmt.runExecute();
            logger.info("executed {} schema statement changed {} rows: {}", label, rowC, statement);
        } catch (SQLException e) {
            if (ignoreErrors) {
                logger.info("ignoring {} error '{}' for statement: {}", label, e, statement);
            } else {
                throw SqlExceptionUtil.create("SQL statement failed: " + statement, e);
            }
        } finally {
            IOUtils.closeThrowSqlException(compiledStmt, "compiled statement");
        }
        // sanity check
        if (rowC < 0) {
            if (!returnsNegative) {
                throw new SQLException(
                        "SQL statement " + statement + " updated " + rowC + " rows, we were expecting >= 0");
            }
        } else if (rowC > 0 && expectingZero) {
            throw new SQLException("SQL statement updated " + rowC + " rows, we were expecting == 0: " + statement);
        }
        stmtC++;
    }
    return stmtC;
}
 
Example 15
Source File: JdbcPooledConnectionSource.java    From ormlite-jdbc with ISC License 5 votes vote down vote up
/**
 * This should be inside of synchronized (lock) stanza.
 */
protected void closeConnection(DatabaseConnection connection) throws SQLException {
	// this can return null if we are closing the pool
	ConnectionMetaData meta = connectionMap.remove(connection);
	IOUtils.closeThrowSqlException(connection, "SQL connection");
	logger.debug("closed connection {}", meta);
	closeCount++;
}
 
Example 16
Source File: RawResultsImpl.java    From ormlite-core with ISC License 5 votes vote down vote up
@Override
public T getFirstResult() throws SQLException {
	try {
		if (iterator.hasNextThrow()) {
			return iterator.nextThrow();
		} else {
			return null;
		}
	} finally {
		IOUtils.closeThrowSqlException(this, "raw results iterator");
	}
}
 
Example 17
Source File: TableUtils.java    From ormlite-core with ISC License 5 votes vote down vote up
private static int doStatements(DatabaseConnection connection, String label, Collection<String> statements,
		boolean ignoreErrors, boolean returnsNegative, boolean expectingZero) throws SQLException {
	int stmtC = 0;
	for (String statement : statements) {
		int rowC = 0;
		CompiledStatement compiledStmt = null;
		try {
			compiledStmt = connection.compileStatement(statement, StatementType.EXECUTE, noFieldTypes,
					DatabaseConnection.DEFAULT_RESULT_FLAGS, false);
			rowC = compiledStmt.runExecute();
			logger.info("executed {} table statement changed {} rows: {}", label, rowC, statement);
		} catch (SQLException e) {
			if (ignoreErrors) {
				logger.info("ignoring {} error '{}' for statement: {}", label, e, statement);
			} else {
				throw SqlExceptionUtil.create("SQL statement failed: " + statement, e);
			}
		} finally {
			IOUtils.closeThrowSqlException(compiledStmt, "compiled statement");
		}
		// sanity check
		if (rowC < 0) {
			if (!returnsNegative) {
				throw new SQLException(
						"SQL statement " + statement + " updated " + rowC + " rows, we were expecting >= 0");
			}
		} else if (rowC > 0 && expectingZero) {
			throw new SQLException("SQL statement updated " + rowC + " rows, we were expecting == 0: " + statement);
		}
		stmtC++;
	}
	return stmtC;
}
 
Example 18
Source File: MappedPreparedStmt.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Assign arguments to the statement.
 * 
 * @return The statement passed in or null if it had to be closed on error.
 */
private CompiledStatement assignStatementArguments(CompiledStatement stmt) throws SQLException {
	boolean ok = false;
	try {
		if (limit != null) {
			// we use this if SQL statement LIMITs are not supported by this database type
			stmt.setMaxRows(limit.intValue());
		}
		// set any arguments if we are logging our object
		Object[] argValues = null;
		if (logger.isLevelEnabled(Level.TRACE) && argHolders.length > 0) {
			argValues = new Object[argHolders.length];
		}
		for (int i = 0; i < argHolders.length; i++) {
			Object argValue = argHolders[i].getSqlArgValue();
			FieldType fieldType = argFieldTypes[i];
			SqlType sqlType;
			if (fieldType == null) {
				sqlType = argHolders[i].getSqlType();
			} else {
				sqlType = fieldType.getSqlType();
			}
			stmt.setObject(i, argValue, sqlType);
			if (argValues != null) {
				argValues[i] = argValue;
			}
		}
		logger.debug("prepared statement '{}' with {} args", statement, argHolders.length);
		if (argValues != null) {
			// need to do the (Object) cast to force args to be a single object
			logger.trace("prepared statement arguments: {}", (Object) argValues);
		}
		ok = true;
		return stmt;
	} finally {
		if (!ok) {
			IOUtils.closeThrowSqlException(stmt, "statement");
		}
	}
}
 
Example 19
Source File: StatementExecutor.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Update rows in the database.
 */
public int update(DatabaseConnection databaseConnection, PreparedUpdate<T> preparedUpdate) throws SQLException {
	CompiledStatement compiledStatement = preparedUpdate.compile(databaseConnection, StatementType.UPDATE);
	try {
		int result = compiledStatement.runUpdate();
		if (dao != null && !localIsInBatchMode.get()) {
			dao.notifyChanges();
		}
		return result;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}
 
Example 20
Source File: StatementExecutor.java    From ormlite-core with ISC License 5 votes vote down vote up
/**
 * Delete rows that match the prepared statement.
 */
public int delete(DatabaseConnection databaseConnection, PreparedDelete<T> preparedDelete) throws SQLException {
	CompiledStatement compiledStatement = preparedDelete.compile(databaseConnection, StatementType.DELETE);
	try {
		int result = compiledStatement.runUpdate();
		if (dao != null && !localIsInBatchMode.get()) {
			dao.notifyChanges();
		}
		return result;
	} finally {
		IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
	}
}