Fixing SQL Injection in JSP and Oracle

Note: This post is part of our series on “How to Fix SQL Injection Vulnerabilities“. The series contains examples on how to fix SQL Injection Vulnerabilities in various programming languages.

An SQL Injection attack is a code injection attack when input from an attacker reaches one of your databases without any filteration or validation. As a result, a malicious user can execute Read / Write / Delete / Update query in your database. In addition to this he can also run system level commands. The following example shows how JSP can be used to interact with an Oracle database to retrieve values based on user input. Using the following methods you can filter any malicious input from the user thereby preventing any possible SQL Injection.

 

Parameterized Query

<pre>
// Prepare a query containing a bind variable.
   String sql = "SELECT * FROM emp WHERE dept = ? ORDER BY empno";
   PreparedStatement stmt = conn.prepareStatement(sql);

// Bind the value into the prepared statement.
   stmt.setInt(1, new Integer(dept).intValue());

// Execute the completed statement.
   ResultSet rs  = stmt.executeQuery();