From a security validation perspective, is there a difference between:
stmt.setObject(1, theObject);
and
stmt.setString(1, theObject);
?
I know that in this case theObject
is a String
but I am interested in making part of this code more general to cover other cases and was wondering if the security perspective of input validation is affected
Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack.
So using prepared statements is safe from SQL injection, as long as you aren't just doing unsafe things elsewhere (that is constructing SQL statements by string concatenation).
What is the advantage of using PreparedStatement? PreparedStatement objects are used to execute repetitive SQL statements. Compared to Statement object execution, Prepared Statement object creation is faster. The reason is the object is pre compiled, by eliminating the compilation task by DBMS.
Prepared statements can protect only data literals, but cannot be used with any other query part.
It is ok to use ssetObject()
because jdbc will try to to do the type resolution for all java.lang.*
types.
However, there is potential problem with passing an arbitrary SQL string to the database in this way - Security loopholes: without very judicious validation of any parameters that you use to build up the SQL string, you are liable to various types of SQL insertion attacks.
Beware of passing untyped null
to setObject()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With