Difference between PreparedStatement batch and Statement batch

大城市里の小女人 提交于 2020-05-29 08:26:24

问题


I'm learning JDBC at the moment and I already know the difference between PreparedStatement and Statement. It is that PreparedStatement is precompiled and allows you to set parameters, but I was asked a question on a job interview about difference between PreparedStatement batch and Statement batch?


回答1:


The difference between batch execution of a Statement and PreparedStatement, is that a Statement batch can contain different statements (as long as they are statements that do not produce a result set), for example a single batch can contain all kinds of inserts into various tables, deletes, updates, and - not in all JDBC driver implementations AFAIK - even DDL statements.

On the other hand, a PreparedStatement batch execution concerns a single statement, and the batch contains the multiple sets of parameter values to execute for that statement. That is, each batch entry defines the values to use for the parameters of the prepared statement.

In short:

  • Statement: batch can contain a lot of different statements
  • PreparedStatement: single statement, multiple sets of parameter values



回答2:


Statement is used for executing a static SQL statement and returning the results it produces.

In PreparedStatement, a SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times. As sql statement is already compiled you will saved some time.

PreparedStatement interface extends Statement interface.

public interface PreparedStatement extends Statement

Batch Processing:

Batch Processing means the batch will be done in "all at once". In batch you can execute multiple statement in single transaction instead of executing them one by one. It will also improve performance because you are making one round trip to database server to insert multiple records instead of multiple trips.

executeBatch() API is a part of Statement interface which submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

You create multiple statement/preparedstatment and add it to a batch. To execute it instead of

statement.execute();  //executes single statement/preparedstatement

you call

 statement.addBatch();  //to add statement to batch
 statement.executeBatch(); //executes batch of statement/preparedstatement

As SQL is pre-compiled and cannot be changed in preparedstatement, batch will same SQL multiple times whereas in case of Statement, you can add different SQLs to batch.



来源:https://stackoverflow.com/questions/42397522/difference-between-preparedstatement-batch-and-statement-batch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!