Created
December 16, 2016 06:36
-
-
Save ruseel/e10bd3fee3c2b165044317f5378c7446 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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