12
I always read the blog Java Revisited and I’ve been reading the article today Why use Preparedstatement in Java JDBC - Example Tutorial. At a certain point the author talks about parameterization of queries, which is better, safer and more performative to use the parameterization offered by the API than concatenating Strings and using the examples below:
SQL Query 1: Preparedstatement using String concatenation
String loanType = getLoanType();
PreparedStatement pstmt = conn.prepareStatement("select banks from loan where loan_type = " + loanType);
SQL Query 2: Query parameterized using Preparedstatement
PreparedStatement pstmt = conn.prepareStatement("select banks from loan where loan_type = ?");
prestmt.setString(1, loanType);
He explains that when using the parameterization the JDBC driver will check the data and with String concatenated no, it will just run the SQL sent, ie if we have that famous OR 1 = 1
the query will always return true and there is the famous SQL Injection.
What was not very clear to me is because one is more performative than the other and more, this would be worth it in case I have an always static parameter too, for example:
PreparedStatement pstmt = conn.prepareStatement(select * from usuarios where ativo = 'S');
Or is it more performative to use as below:
PreparedStatement pstmt = conn.prepareStatement(select * from usuarios where ativo = ?);
pstmt.setString(1, "S");
Another question, in this case I think the security issue is the same, because as there is no parameter passage through the user there is no way to have the attack, right?
TL;DR for question or blog?
– Philippe Gioseffi
For his answer :)
– Rodrigo Rigotti
I saw this on some Stackexchange sites in English and adopted it. At first I found it strange, but then I realized that TL;DR can also be used to summarize your own content.
– utluiz