Common:
Both PreparedStatement and statement are one of the APIs used to execute SQL query statements.
Different points:
In PreparedStatement, when we often need to execute a similar SQL statement repeatedly, such as:
Insert into Table Values (0,'first',1); Insert into Table Values (0,'second',2);
We can use SQL with placeholders instead of it:
Insert into Table Values (0,?,?);
The arguments are then passed each time, but placeholders are not allowed in statement, and no parameters are used. And more importantly, PreparedStatement will precompile the SQL statement, the pre-compiled SQL statements exist in the object, so that each pass-through parameters to execute the query will become very efficient, that is to say PreparedStatement is more efficient than statement. PreparedStatement also provides a series of setxxx (int index, XXX value) methods to pass in parameters.
preparedstatement can prevent SQL injection attacks:
(The following sections refer to Wikipedia: Http://zh.wikipedia.org/wiki/SQL%E8%B3%87%E6%96%99%E9%9A%B1%E7%A2%BC%E6%94%BB%E6%93%8A)
For example, a website's login verification SQL query code is:
strSQL = "SELECT * from users WHERE name = '" + userName + "' and pw = '" + PassWord + "';"
Malicious filling in:
UserName = "1 ' or ' 1 ' = ' 1"= "1 ' or ' 1 ' = ' 1";
Then the final SQL statement becomes:
strSQL = "SELECT * from users WHERE name = ' 1 ' or ' 1 ' = ' 1 ' and pw = ' 1 ' or ' 1 ' = ' 1 ';"
Because where conditions are constant, this is equivalent to executing:
strSQL = "SELECT * from Users;"
So you can access the website without an account password.
have already logged into the database, what do you want to do in the back to control it?
However, a parameterized query using PreparedStatement can block most SQL injections. In the case of parameterized queries, the database does not treat the contents of the parameter as part of the SQL instruction, but only when the database has completed compiling the SQL instructions, so that the parameters are not run by the database, even if they contain destructive instructions.
This blog content and code are the author Jarvis original, if reproduced please specify.
The difference between PreparedStatement and statement in JDBC