I use this class to run sql query with parameter
/* @author adam_crume
*/
public class NamedParameterStatement {
/** The statement this object is wrapping. */
private final PreparedStatement statement;
/** Maps parameter names to arrays of ints which are the parameter indices.
*/
private final Map indexMap;
/**
* Creates a NamedParameterStatement. Wraps a call to
* c.{@link Connection#prepareStatement(java.lang.String)
prepareStatement}.
* @param connection the database connection
* @param query the parameterized query
* @throws SQLException if the statement could not be created
*/
public NamedParameterStatement(Connection connection, String query) throws
SQLException {
indexMap=new HashMap();
String parsedQuery=parse(query, indexMap);
statement=connection.prepareStatement(parsedQuery);
}
/**
* Parses a query with named parameters. The parameter-index mappings are
put into the map, and the
* parsed query is returned. DO NOT CALL FROM CLIENT CODE. This
method is non-private so JUnit code can
* test it.
* @param query query to parse
* @param paramMap map to hold parameter-index mappings
* @return the parsed query
*/
static final String parse(String query, Map paramMap) {
// I was originally using regular expressions, but they didn't work well for ignoring
// parameter-like strings inside quotes.
int length=query.length();
StringBuffer parsedQuery=new StringBuffer(length);
boolean inSingleQuote=false;
boolean inDoubleQuote=false;
int index=1;
for(int i=0;i
example to use this class :
...
NamedParameterStatement p = new NamedParameterStatement(tempConn, "SELECT username, password FROM username WHERE username = :paramUsername");
p.setString("paramUsername", txtUsername.getText());
ResultSet tempRs = p.executeQuery();
...
Reference : http://www.javaworld.com/article/2077706/core-java/named-parameters-for-preparedstatement.html