In the second example, the query structure is defined
using a question mark
as a placeholder for the user-supplied parameter. The
prepareStatement
method is invoked to interpret this, and fix the structure of the query that is to
be executed. Only then is the
setString
method used to specify the actual
value of the parameter. Because the query’s structure has already been fixed,
this value can contain any data at all, without affecting the structure. The
query is then executed safely:
//define the query structure
String queryText = “SELECT ename,sal FROM EMP WHERE ename = ?”;
//prepare the statement through DB connection “con”
stmt = con.prepareStatement(queryText);
//add the user input to variable 1 (at the first ? placeholder)
stmt.setString(1, request.getParameter(“name”));
// execute the query
rs = stmt.executeQuery();
N OT E
Do'stlaringiz bilan baham: