I am working with java + mysql. I have the following piece of code:
String sql = "INSERT INTO tableA (id, age) VALUES (1, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
stmt.setString(age);
stmt.execute();
Assuming that the String age :-( is an input from user, I would hope that the above code prevents SQL injection. I found out that mysql driver does not allow to multiple queries in one statement, so inputs like
76); Drop table tableB; -- )
would be rejected by mysql, even if I am not using prepared statements. However, in the latter case an input like
(select id from tableB where age = 10) // lets assume this returns 20
would be accepted inserting (1, 20) in the database. By using preparedStatement in the way I have described above, I am expecting that this kind of input would get rejected preventing a SQL Injection attack. However, what I see is very weird. I am not sure if this subquery is executed or not, but what I see is a record (1, 0) being inserted in the database. I am expecting that I should rather get an exception from mysql here.
At this point I am totally confused. Any thoughts? Am I correct with my assumptions ? Thanks for your help.