I developed a function that allows you to use named parameters in your SQL queries:
private PreparedStatement generatePreparedStatement(String query, Map<String, Object> parameters) throws DatabaseException { String paramKey = ""; Object paramValue = null; PreparedStatement statement = null; Pattern paramRegex = null; Matcher paramMatcher = null; int paramIndex = 1; try { //Create the condition paramRegex = Pattern.compile("(:[\\d\\w_-]+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); paramMatcher = paramRegex.matcher(query); statement = this.m_Connection.prepareStatement(paramMatcher.replaceAll("?"), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); //Check if there are parameters paramMatcher = paramRegex.matcher(query); while (paramMatcher.find()) { paramKey = paramMatcher.group().substring(1); if(parameters != null && parameters.containsKey(paramKey)) { //Add the parameter paramValue = parameters.get(paramKey); if (paramValue instanceof Date) { statement.setDate(paramIndex, (java.sql.Date)paramValue); } else if (paramValue instanceof Double) { statement.setDouble(paramIndex, (Double)paramValue); } else if (paramValue instanceof Long) { statement.setLong(paramIndex, (Long)paramValue); } else if (paramValue instanceof Integer) { statement.setInt(paramIndex, (Integer)paramValue); } else if (paramValue instanceof Boolean) { statement.setBoolean(paramIndex, (Boolean)paramValue); } else { statement.setString(paramIndex, paramValue.toString()); } } else { throw new DatabaseException("The parameter '" + paramKey + "' doesn't exists in the filter '" + query + "'"); } paramIndex++; } } catch (SQLException l_ex) { throw new DatabaseException(tag.lib.common.ExceptionUtils.getFullMessage(l_ex)); } return statement; }
You can use it as follows:
Map<String, Object> pars = new HashMap<>(); pars.put("name", "O'Really"); String sql = "SELECT * FROM TABLE WHERE NAME = :name";
source share