ce problème sournoise ignobles, merci entièrement il est assez facile de faire face à:
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;
}
}
Pour utiliser, il suffit d'écrire une classe anonyme qui remplace preparePrepared void (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! Vous avez maintenant un moyen de travailler avec un PreparedStatement sans l'avoir encore construit. Voici un exemple montrant la boilerplate minimale que vous auriez autrement à copier coller au règne vienne, chaque fois que vous vouliez écrire une déclaration différente:
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); }
}
}
Vous avez vraiment ne voulez vraiment pas être coller copie que partout, le faites vous?
Cette bibliothèque importe le paquet "com.healthmarketscience.common.util" qui n'est pas inclus ... – r3zn1k
Vous devez faire un petit tour: http://openhms.sourceforge.net/common-util/ – PeterMmm
Meilleure solution. Merci beaucoup! – r3zn1k