Search code examples
javamysqlprepared-statementsanitization

Prepared statement needed if the user data format was changed?


I use JCalendarChooser and user data was in d MMMM yyyy format. Example output is 4 November 2015. Before I SELECT from database I change it to yyyy-MM-dd format. This is my code before SELECT:

                String date1 = null;

                java.util.Date d1 = jDateChooser1.getDate();
                if (d1 == null) {
                    System.out.println("No date specified!");
                } else {
                    DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                    date1 = fmt.format(d1); //jdatechooser
                    // Then select from db
                }

The way I understand about user validation is you need to sanitize all input from user but what if the data format was changed? Do I need to use prepared statements in such case above?

Thanks in advance


Solution

  • If there is no other way for input to get from the user to the query except by passing through (and being validated by) the jDateChooser and SimpleDateFormat, then your input is adequately sanitized.

    That said, there are other reasons to use a PreparedStatement over a dynamic SQL string. If you run the same query multiple times with different dates, then each dynamic SQL string thus produced will be regarded by the dbms as a new query to be compiled from scratch, while a PreparedStatement will produce a single fill-in-the-blanks execution plan which can be reused without recompilation. This can result in improved performance on an oft-repeated query, which is A Good Thing™.