This is another debated subject, but this time i am searching only for the simple and documented answers. The scenario :
Let\'s assume the following method:
Do not build SQL queries by concatenating strings, like you're doing:
sql = new StringBuffer();
sql.append("SELECT * FROM ").append("dogs_table");
sql.append(" WHERE ").append(colName).append("='");
sql.append(colValue).append("'");
This makes your code vulnerable to a well-known security attack, SQL injection. Instead of doing this, use a PreparedStatement
and set the parameters by calling the appropriate set...()
methods on it. Note, you can only use this to set column values, you can't use this to dynamically construct a column name, as you're doing. Example:
PreparedStatement ps = connection.prepareStatement("SELECT * FROM dogs_table WHERE MYCOL=?");
ps.setString(1, colValue);
rs = ps.executeQuery();
If you use a PreparedStatement
, the JDBC driver will automatically take care of escaping certain characters that might be present in colValue
, so that SQL injection attacks don't work anymore.