Why Prepared Statement is faster than Statement in Java.
Prepared Statement is faster than Statement in Java. Prepared Statement is better because it caches query so is fast and prevents from SQL Injection.
This is the famous interview question for the beginners, So Let's see what it is all about.
SQL Injection is code injection technique where SQL is injected by user (as part of user input) into the back end query, and ultimately changes query purpose which upon execution gives harmful result.
Detailed explanation on SQL Injection: What is SQL Injection?
How can SQL Injection happen.
At server side, queries generally by themselves are not complete and require user data to make it complete, meaningful and executable.
"select * from user where username = ' " + username + " ' ";Above query is not complete as it has dependency on username variable.
Now if username variable is filled by third party, then there are chances that user data contains SQL,
Take an example. Application is asking user to enter user name,
Enter user name:________________________
Enter user name:___jayesh'; delete from user where id='1__
At Server Side,
username = "jayesh'; delete from user where id='1"
Final Query = "select * from user where username = ' jayesh'; delete from user where id='1 ' ";
If you observe final query, upon execution it will delete the record from user table which was never the purpose of original query and this is called SQL Injection attack.
Because of user data (which can be anything and uncontrolled) involvement in formation of query, SQL Injection attack can happen.
Detailed explanation on: How can SQL Injection happen?
How PreparedStatement in Java prevents SQL Injection?
To understand this, Lets see steps involved in query execution.
1. Compilation Phase.
2. Execution Phase.
Whenever SQL server engine receives a query, It has to pass through below phases,






