Using PreparedStatement

The ordinary Statement class is fine for running queries that don't have parameters, but as soon as you need to be able to add Java variables to SQL statements, they get clumsy. For example, let's say that you have a variable called findLast that is holding a string containing a last name. You want to find all the employees with that last name. To do it with a statement, it would have to look like this:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM employees where lname_txt = '" + findLast + "'");

That's an unattractive piece of code, especially because you have to remember to put single quotes around the string value. But worse, if there are “special characters such as ' that are ...

Get MySQL™ and JSP™ Web Applications: Data-Driven Programming Using Tomcat and MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.