@@ -0,0 +1,1696 @@
+import java.sql.Connection;%0Aimport java.sql.ResultSet;%0Aimport java.sql.SQLException;%0Aimport java.sql.Statement;%0Aimport java.util.Map;%0Aimport java.util.HashMap;%0A%0A// Contributed by Matt Hargett, http://www.clock.org/~matt%0A%0Apublic class NoSqlInjection %7B%0A%09private static final String%5B%5D COLUMNS = new String%5B%5D %7B%22ID%22, %22NAME%22%7D;%0A%09private static final String%5B%5D PREFIXES = new String%5B%5D %7B%22GOPHER%22, %22LLAMA%22%7D;%0A%09private Connection connection;%0A%0A%09public NoSqlInjection(Connection connection) %7B%0A%09%09this.connection = connection;%0A%09%7D%0A%0A%09public void beSafe() throws SQLException %7B%0A%09%09Statement query = connection.createStatement();%0A%09%09query.executeQuery(%22select * from ANIMAL%22);%0A%09%09ResultSet zooResults = query.getResultSet();%0A%0A%09%09String columnString = %22TYPE, ANIMAL_ID%22;%0A%09%09for (String handlerColumn : COLUMNS) %7B%0A%09%09%09columnString += %22, %22 + handlerColumn;%0A%09%09%7D%0A%09%09while (zooResults.next()) %7B%0A%09%09%09for (String prefix : PREFIXES) %7B%0A%09%09%09%09String valuesString = %22%22;%0A%09%09%09%09if (prefix.equals(%22GOPHER_%22)) %7B%0A%09%09%09%09%09valuesString += %22'PLATYPUS'%22;%0A%09%09%09%09%7D else if (prefix.equals(%22LLAMA_%22)) %7B%0A%09%09%09%09%09valuesString += %22'DOLLY'%22;%0A%09%09%09%09%7D%0A%0A%09%09%09%09valuesString += %22,%22 + prefix;%0A%0A%09%09%09%09for (String column : COLUMNS) %7B%0A%09%09%09%09%09valuesString += %22,%22 + column;%0A%09%09%09%09%7D%0A%0A%09%09%09%09connection.createStatement().executeUpdate(%22insert into HANDLER (%22 + columnString + %22) VALUES (%22 + valuesString + %22);%22);%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D%0A%09%0A%09public void beSafeSimple() throws SQLException %7B%0A%09%09Statement query = connection.createStatement();%0A%09%09query.executeQuery(%22select * from ANIMAL%22);%0A%09%09ResultSet zooResults = query.getResultSet();%0A%0A%09%09String columnString = %22TYPE, ANIMAL_ID%22;%0A%09%09connection.createStatement().executeUpdate(%22insert into HANDLER (%22 + columnString + %22) VALUES (%22 + PREFIXES%5B0%5D + %22);%22);%0A%09%7D%0A%7D%0A%0A

Add test case contributed by Matt Hargett