Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a dastardly devious problem, thankfully it's pretty easy to cope with:</p> <pre><code>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; } } </code></pre> <p>To use, just write an anonymous class that overrides void preparePrepared(PreparedStatement):</p> <pre><code> 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); </code></pre> <p>Presto! You now have a way to work with a PreparedStatement without yet having built it. Here's an example showing the minimal boilerplate you'd otherwise have to copy paste to kingdom come, every time you wanted to write a different statement: </p> <pre><code>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); } } } </code></pre> <p>You really really don't want to be copy pasting that everywhere, do you?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload