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

net.sf.gluebooster.java.booster.basic.container.ParameterizedStatement Maven / Gradle / Ivy

Go to download

Basic classes to support the development of applications. There should be as few dependencies on other frameworks as possible.

The newest version!
package net.sf.gluebooster.java.booster.basic.container;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.sf.gluebooster.java.booster.basic.db.ResultSetIterator;
import net.sf.gluebooster.java.booster.basic.db.Sql;

/**
 * Configuration of a statement with parameters
 * 
 * @defaultParamText statement the statement that is parameterized.
 * @defaultParamText parameters the parameters of the statement
 * 
 * @author cbauer
 *
 */
public class ParameterizedStatement {

	/**
	 * the type of the statement
	 */
	private Object type;
	
	/**
	 * the statement that is parameterized.
	 */
	private String statement;
	
	/**
	 * the parameters of the statement
	 */
	private List parameters;

	/**
	 * Constructor without parameters
	 */
	public ParameterizedStatement(Object type, String statement) {
		this.statement = statement;
		this.type = type;
		parameters = new ArrayList<>();
	}

	/**
	 * Constructor with parameters
	 */
	public ParameterizedStatement(Object type, String statement, Object... parameters) {
		this(type, statement);
		if (parameters != null && parameters.length > 0) {
			this.parameters = Arrays.asList(parameters);
		}
	}

	/**
	 * Executes this statement as sql
	 * @param connection the database connection
	 * @return the result of the statement a ResultSetIterator (Select), an int value (update), 
	 */
	public Object execSql(Connection connection) throws Exception {
		Statement sql = connection.createStatement();
		PreparedStatement prep = connection.prepareStatement(statement);
		int i = 1;
		for (Object param : parameters) {
			prep.setObject(i++, param);
		}
		if (Sql.QUERY.equals(type)) {
			ResultSet sqlResult = prep.executeQuery();// sql.executeQuery(statement);
			return new ResultSetIterator(sqlResult);
		} else if (Sql.UPDATE.equals(type)) {
			return prep.executeUpdate();

		} else {
			throw new IllegalStateException("type not supported: " + type);
		}
	}

	public Object getType() {
		return type;
	}

	public void setType(Object type) {
		this.type = type;
	}

	public String getStatement() {
		return statement;
	}

	public void setStatement(String statement) {
		this.statement = statement;
	}

	public List getParameters() {
		return parameters;
	}

	public void setParameters(List parameters) {
		this.parameters = parameters;
	}

}