Software

Java: sfruttarlo al meglio con le prepared statements

Michele Costabile | 27 Giugno 2017

La classe base import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Collections; import java.util.List; import java.util.logging.Logger; public abstract class AbstractAdder { […]

La classe base

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
public abstract class AbstractAdder {
protected static Logger logger = Logger.getLogger(“it.dapsides.logistics.ftp”);
protected Connection connection;
protected String SQL;
protected String tableName;
protected PreparedStatement pstmt;
protected List<String> fields;

public AbstractAdder(Connection connection) {
super();
this.connection = connection;
}
/**
* crea una query string da una lista di campi, calcolando il numero giusto
* di punti interrogativi per i parametri
*
* @throws SQLException
*/
public void prepare() throws SQLException {
// prepareStatement();
SQL = “insert into ” + tableName + ” ( ” + String.join(“, “, fields) + ” ) values ( “+ String.join(“, “, Collections.nCopies(fields.size(), “?”)) + ” )”;
logger.info(SQL);
pstmt = connection.prepareStatement(SQL);
}

public abstract void update() throws SQLException;
/**
* trova l’ordine di una colonna in una query, controllando che il campo
* esista. Restituisce un indice 1-based.
*
* @param fieldName
* @return indice della colonna
* @throws IllegalArgumentException
*/

public int fieldNo(String fieldName) throws IllegalArgumentException {
int index = fields.indexOf(fieldName);
if (index >= 0)
return index + 1;
else
throw new
IllegalArgumentException(“Field ” + fieldName + ” not present in query string”);
}
}

< Indietro Successivo >