To prevent a SQL-Injection, one should use prepared statements instead of normal statements. Why? Because a variable's SQL-metacharacters, passed as arguments to prepared statements, will automatically be escaped by the JDBC driver.
Example:
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
Incorrect usage of prepared statements can render their protective aspect inert.
Example:
String strUserName = request.getParameter("Txt_UserName");
PreparedStatement prepStmt = con.prepareStatement("SELECT * FROM user WHERE userId = '+strUserName+'");