All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.objectos.db.SqlStatement Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2015 Objectos, Fábrica de Software LTDA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package br.com.objectos.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author [email protected] (Marcio Endo)
 */
public class SqlStatement implements AutoCloseable {

  private final PreparedStatement statement;
  private final List openResultList = new ArrayList<>(2);

  SqlStatement(PreparedStatement statement) {
    this.statement = statement;
  }

  public SqlStatement addBatch() {
    try {
      statement.addBatch();
      return this;
    } catch (SQLException e) {
      throw SqlRuntimeException.wrap(e);
    }
  }

  @Override
  public void close() {
    Iterator resultIterator = openResultList.iterator();

    while (resultIterator.hasNext()) {
      Result rs = resultIterator.next();
      rs.close();
      resultIterator.remove();
    }

    try {
      statement.close();
    } catch (SQLException e) {
    }
  }

  public int[] executeBatch() {
    try {
      return statement.executeBatch();
    } catch (SQLException e) {
      throw SqlRuntimeException.wrap(e);
    }
  }

  public Result executeQuery() {
    try {
      ResultSet rs = statement.executeQuery();
      Result ret = Result.of(rs);
      openResultList.add(ret);
      return ret;
    } catch (SQLException e) {
      throw SqlRuntimeException.wrap(e);
    }
  }

  public int executeUpdate() {
    try {
      return statement.executeUpdate();
    } catch (SQLException e) {
      throw SqlRuntimeException.wrap(e);
    }
  }

  public Result generatedKeys() {
    try {
      ResultSet rs = statement.getGeneratedKeys();
      Result ret = Result.of(rs);
      openResultList.add(ret);
      return ret;
    } catch (SQLException e) {
      throw SqlRuntimeException.wrap(e);
    }
  }

  public PreparedStatementBinder parameterBinder() {
    return new PreparedStatementBinder(this, statement);
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy