// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.FormatProcessor;

public class SqlInjectD {
    public static class PreparedStatementFormatter implements StringTemplate.Processor<PreparedStatement, SQLException> {
        private Connection con;
        public PreparedStatementFormatter(Connection con) {
            this.con = con;
        }
        @Override
        public PreparedStatement process(StringTemplate st) throws SQLException {
            PreparedStatement pstmt = con.prepareStatement(String.join("?", st.fragments()));
            for(int i = 0; i < st.values().size(); i++) {
                switch(st.values().get(i)) {
                    case Integer iv -> pstmt.setInt(i + 1, iv);
                    case Double xv -> pstmt.setDouble(i + 1, xv);
                    case String sv -> pstmt.setString(i + 1, sv);
                    default -> throw new SQLException("Unsupported type");
                }
            }
            return pstmt;
        }
    }
    private static void test(Connection con, String f2) throws SQLException {
        PreparedStatementFormatter pstmtfmt = new PreparedStatementFormatter(con);
        try(PreparedStatement pstmt = pstmtfmt."SELECT COUNT(*) FROM t1 WHERE f2 = \{f2}") {
            try(ResultSet rs = pstmt.executeQuery()) {
                rs.next();
                System.out.println(rs.getInt(1));
            }
        }
    }
    public static void main(String[] args) throws Exception {
        try(Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Test", "root", "hemmeligt")) {
            test(con, "BB");
            test(con, "BB' OR 'X'='X");
        }
    }
}
