Hello friends! I am writing this post to share a very common security vulnerability that can be exploited by intruders. It is SQL Injection.
What is SQL Injection ?
SQL injection happens when you insert some content into a SQL query string, and the result modifies the syntax of your query in ways you didn’t intend.
Example of a vulnerable Usage:-
String query = "SELECT * FROM users WHERE userid ='"+ userid + "'" + " AND password='" + password + "'"; Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(query);
This code is vulnerable to SQL Injection because we can insert an SQL syntax into the variable “userid” like OR ‘1’=’1′ which makes the result of whole SQL expression true.
How to Prevent it ?
In order to prevent it we can use a concept called prepared statement. A PreparedStatement is nothing but a precompiled SQL statement that can be executed multiple times without recompiling again and again.
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE userid=? AND password=?"); stmt.setString(1, userid); stmt.setString(2, password); ResultSet rs = stmt.executeQuery();
This above code is not vulnerable to SQL Injection because it uses parameterized queries. By utilizing Java’s PreparedStatement class, bind variables (i.e. the question marks) and the corresponding setString methods, SQL Injection can be easily prevented.