Differences and usage comparison between Statement and PreparedStatement in java

Source: Internet
Author: User


1. PreparedStatement is pre-compiled, which greatly improves the efficiency of batch processing. It is also called the JDBC stored procedure.

2. Use the Statement object. When only one-time access is performed to the database, the Statement object is used for processing. The overhead of the PreparedStatement object is greater than that of the Statement object, which does not bring additional benefits to one-time operations.
 
3. Each time statement executes an SQL statement, the relevant database must compile the SQL statement. preparedstatement is pre-compiled, and preparedstatement supports batch processing.

Code Fragment 1:

String updateString = "update coffees set sales = 75" + "WHERE COF_NAME LIKE 'Colombian'" ;stmt.exe cuteUpdate (updateString); Code Fragment 2: PreparedStatement updateSales = con. prepareStatement ("update coffees set sales =? WHERE COF_NAME LIKE? "); UpdateSales. setInt (1, 75); updateSales. setString (2," Colombian ");updateSales.exe cuteUpdate ();

The difference between Segment 2 and segment 1 is that the latter uses the PreparedStatement object, while the former is a common Statement object. The PreparedStatement object not only contains the SQL statement, but also has been pre-compiled in most cases. Therefore, when executing the statement, you only need to run the SQL statement in the DBMS instead of compiling it first. When you need to execute the Statement object multiple times, the PreparedStatement object will greatly reduce the running time and, of course, speed up database access.
This conversion also brings you great convenience. You do not have to repeat the syntax of SQL statements. Instead, you only need to change the value of the variable to execute the SQL statement again. Whether the PreparedStatement object is selected depends on whether the SQL statements with the same syntax are executed multiple times, and the difference between the two statements is only the difference between variables. If it is executed only once, it should be no different from ordinary objects, and it does not reflect the superiority of its pre-compilation.
5. JDBC programs that execute many SQL statements generate a large number of Statement and PreparedStatement objects. The PreparedStatement object is generally considered to be more effective than the Statement object, especially when the same SQL Statement with different parameters is executed multiple times. The PreparedStatement object allows the database to pre-compile SQL statements, saving time and increasing code readability in subsequent operations.

However, in the Oracle environment, developers are actually more flexible. When Statement or PreparedStatement object is used, the Oracle database caches SQL statements for later use. In some cases, execution of the PreparedStatement object takes a longer time because the drive itself requires additional processing and added network activity between the Java application and the Oracle server.

However, in addition to Buffering, there is at least one better reason for us to prefer PreparedStatement objects in enterprise applications, that is, security. Parameters passed to the PreparedStatement object can be forcibly converted, so that developers can ensure that they match the underlying database format when inserting or querying data.

When processing data from users on a public Web site, security issues become extremely important. The string parameter passed to PreparedStatement is automatically ignored by the drive. In the simplest case, this means that when your program tries to insert the string "D 'Angelo" into VARCHAR2, this statement will not recognize the first ",", this leads to a miserable failure. There is almost no need to create your own strings to ignore the code.

In the Web environment, malicious users use applications that are poorly designed and cannot correctly process strings. Especially on public websites, all user input should not be passed to SQL statements without PreparedStatement object processing. In addition, SQL statements should not be displayed when users have the opportunity to modify SQL statements, such as HTML hidden areas or a query string.


Differences between PreparedStatement and Statement

1. The PreparedStatement interface inherits Statement. The PreparedStatement instance contains compiled SQL statements, so the execution speed is faster than the Statement object. 2. As a subclass of Statement, PreparedStatement inherits all functions of Statement. Three methods
Execute, executeQuery, and executeUpdate have been changed so that they no longer need parameters.


3. In JDBC applications, if you are already a relatively level developer, you should always use PreparedStatement instead.

Statement. That is to say, do not use Statement at any time.
For the following reasons:

I. Code readability and maintainability.

Although the use of PreparedStatement instead of Statement will lead to several more lines of code, such code is much higher than the use of Statement code in terms of readability and maintainability:

Tmt.exe cuteUpdate ("insert into tb_name (col1, col2, col2, col4) values ('" + var1 + "', '" + var2 + "'," + var3 + ", '"+ var4 +"') "); // stmt is

 

Statement object instance

Perstmt = con. prepareStatement ("insert into tb_name (col1, col2, col2, col4) values (?,?,?,?) "CuteUpdate (); // prestmt is an instance of the PreparedStatement object.

I don't need to talk about it. For the first method, don't let others read your code. It means you will feel sad if you read your code later.

2. PreparedStatement to maximize performance.
If the statement is cached by the execution code compiled by the DB compiler, you do not need to compile the statement as long as it is the same pre-compiled statement in the next call, you only need to pass the parameters directly into the compiled statement execution code (equivalent to a number of Han) and the code will be executed. this does not mean that only the pre-compiled statements executed multiple times in a Connection are cached. Instead, if the pre-compiled statement syntax matches the cache. at any time, you can directly execute it without re-compiling. in statement statements, even if they are the same operation, the chance of matching the entire statement is very small because the data of each operation is different, and it is almost impossible to match the statement. for example:

Insert into tb_name (col1, col2) values ('11', '22'); insert into tb_name (col1, col2) values ('11', '23 ');

Even if the operation is the same, but because the data content is different, the entire statement itself cannot match and has no significance for cache statements. The fact is that no database will cache the code executed after compilation of common statements.

Of course, not all pre-compiled statements will be cached. The database itself will use a policy, such as the usage frequency, to determine when to stop caching the existing pre-compiled results. to store more space for new pre-compiled statements.

3. The most important thing is to greatly improve security.

Even so far, some people still do not know the basic SQL syntax.

String SQL = "select * from tb_name where name = '" + varname + "' and passwd = '" + varpasswd + "'";

If we pass in ['or '1' = '1] as varpasswd, the user name is random and you can see what it will become?

Select * from tb_name = 'free' and passwd = ''or '1' = '1 ';

Because '1' = '1' must be true, any verification can be performed. What's more:
Input ['; drop table tb_name;] as varpasswd. Then:

Elect * from tb_name = 'random 'and passwd = ''; drop table tb_name;

 

Some databases won't let you succeed, but many databases can execute these statements.

 

If you use precompiled statements. nothing you input will match the original statement. as long as pre-compiled statements are fully used, you do not need to worry about the incoming data. however, if you use a common statement, you may need to make painstaking judgment and worry over the drop,; and so on.

Why are you still using PreparedStatement at any time?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.