Java Reference
In-Depth Information
between the two types of connections is the method name that is called in order to ob-
tain the Connection object.
You could develop a JDBC application so that the code used to obtain a connection
needs to be hard-coded throughout. Instead, this solution enables all the code for ob-
taining a connection to be encapsulated by a single class so that the developer does not
need to worry about it. Such a technique also allows the code to become more main-
tainable. For instance, if the application were originally deployed using the Driver-
Manager , but then later had the ability to use a DataSource , very little code would
need to be changed.
13-6. Guarding Against SQL Injection
Problem
Your application performs database tasks. To reduce the chances of a SQL injection at-
tack, you need to ensure that no unfiltered strings of text are being appended to SQL
statements and executed against the database.
Tip Although prepared statements are the solution to this recipe, they can be used
for more than just protecting against SQL injection. They also provide a way to central-
ize and better control the SQL used in an application. Instead of creating multiple, pos-
sibly different, versions of the same query, for example, you can create the query once
as a prepared statement and invoke it from many different places throughout your code.
Any change to the query logic need happen only at the point where you prepare the
statement.
Solution
Use PreparedStatement s for performing the database tasks. PreparedState-
ment s send a precompiled SQL statement to the DBMS rather than a string. The fol-
lowing code demonstrates how to perform a database query and a database update us-
ing a java.sql.PreparedStatement object.
In the following code example, a PreparedStatement is used to query a data-
base for a given record. Assume that the string recipeNumber is passed to this code
as a variable.
Search WWH ::




Custom Search