Skip to content

Instantly share code, notes, and snippets.

@ruseel
Created December 16, 2016 06:36
Show Gist options
  • Save ruseel/e10bd3fee3c2b165044317f5378c7446 to your computer and use it in GitHub Desktop.
Save ruseel/e10bd3fee3c2b165044317f5378c7446 to your computer and use it in GitHub Desktop.
public class NamedParamStatement {
public NamedParamStatement(Connection conn, String statementWithNames) throws SQLException {
Pattern findParametersPattern = Pattern.compile("(?<!')(:[\\w]*)(?!')");
Matcher matcher = findParametersPattern.matcher(statementWithNames);
while (matcher.find()) {
fields.add(matcher.group().substring(1));
}
prepStmt = conn.prepareStatement(statementWithNames.replaceAll(findParametersPattern.pattern(), "?"));
}
public PreparedStatement getPreparedStatement() {
return prepStmt;
}
public ResultSet executeQuery() throws SQLException {
return prepStmt.executeQuery();
}
public void close() throws SQLException {
prepStmt.close();
}
public void setInt(String name, int value) throws SQLException {
prepStmt.setInt(getIndex(name), value);
}
private int getIndex(String name) {
return fields.indexOf(name)+1;
}
private PreparedStatement prepStmt;
private List<String> fields = new ArrayList<String>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment