package database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.joda.time.DateTime; /** * Allows a prepared statement to contain named parameters instead of a question * mark position marker. * * @author Peter Wu */ public class NamedPreparedStatement { private final List fields; private final PreparedStatement stmt; public NamedPreparedStatement(Connection conn, String query) throws SQLException { fields = new ArrayList<>(); Pattern pattern = Pattern.compile("(? getParamIndices(String fieldName) { List indices = new ArrayList<>(); int index = 0; for (String name : fields) { ++index; if (name.equals(fieldName)) { indices.add(index); } } if (indices.isEmpty()) { System.err.println(stmt); throw new RuntimeException("Missing " + fieldName + " in query!"); } return indices; } public void setInt(String name, Integer i) throws SQLException { for (int paramIndex : getParamIndices(name)) { if (i == null) { stmt.setNull(paramIndex, Types.INTEGER); } else { stmt.setInt(paramIndex, i); } } } public void setLong(String name, Long l) throws SQLException { for (int paramIndex : getParamIndices(name)) { if (l == null) { stmt.setNull(paramIndex, Types.BIGINT); } else { stmt.setLong(paramIndex, l); } } } public void setString(String name, String str) throws SQLException { for (int paramIndex : getParamIndices(name)) { stmt.setString(paramIndex, str); } } public void setTimestamp(String name, DateTime dt) throws SQLException { for (int paramIndex : getParamIndices(name)) { Timestamp tsp = new Timestamp(dt.getMillis()); Calendar calendar = dt.toCalendar(Locale.ENGLISH); stmt.setTimestamp(paramIndex, tsp, calendar); } } public void setBoolean(String name, boolean b) throws SQLException { for (int paramIndex : getParamIndices(name)) { stmt.setBoolean(paramIndex, b); } } public PreparedStatement getStmt() { return stmt; } public void executeUpdate() throws SQLException { try { getStmt().executeUpdate(); } catch (SQLException ex) { System.err.println("Query error: " + ex.getMessage()); System.err.println(stmt); throw ex; } } }