questo è un problema subdolo vile, grazie completamente è abbastanza facile da affrontare:
public class PreparedStatementBuilder
{
private String sql; // the sql to be executed
public PreparedStatementBuilder(final String sql) { this.sql = sql; }
protected void preparePrepared(final PreparedStatement preparedStatement)
throws SQLException
{
// this virtual method lets us declare how, when we do generate our
// PreparedStatement, we want it to be setup.
// note that at the time this method is overridden, the
// PreparedStatement has not yet been created.
}
public PreparedStatement build(final Connection conn)
throws SQLException
{
// fetch the PreparedStatement
final PreparedStatement returnable = conn.prepareStatement(sql);
// perform our setup directives
preparePrepared(returnable);
return returnable;
}
}
da usare, basta scrivere una classe anonima che sostituisce vuoto preparePrepared (PreparedStatement):
final String sql = "SELECT * FROM FOO WHERE USER = ?";
PreparedStatementBuilder psBuilder = new PreparedStatementBuilder(sql){
@Override
protected void preparePrepared(PreparedStatement preparedStatement)
throws SQLException
{
preparedStatement.setString(1, "randal");
}};
return obtainResultSet(psBuilder);
Presto! Ora hai un modo di lavorare con un PreparedStatement senza averlo ancora creato. Ecco un esempio che mostra il testo standard minimo si sarebbe altrimenti necessario copiare incollare al regno, ogni volta che si voleva scrivere una dichiarazione diversa:
public ResultSet obtainResultSet(final PreparedStatementBuilder builder)
throws SQLException {
final Connection conn = this.connectionSource.getConnection();
try
{
// your "virtual" preparePrepared is called here, doing the work
// you've laid out for your PreparedStatement now that it's time
// to actually build it.
return builder.build(conn).executeQuery();
}
finally
{
try { conn.close(); }
catch (SQLException e) { log.error("f7u12!", e); }
}
}
Davvero davvero non si vuole essere la copia incolla che ovunque, Fai?
Questa libreria importa il pacchetto "com.healthmarketscience.common.util" che non è incluso ... – r3zn1k
Devi andare in giro un po ': http://openhms.sourceforge.net/common-util/ – PeterMmm
Soluzione migliore. Grazie mille! – r3zn1k