Explain the commit and rollback of transactions in Java’s JDBC API in detail

If the JDBC connection is in auto commit mode and it is in default, each SQL statement is submitted to the database when it is completed.

This may be for simple applications, but there are three reasons why you may want to turn off automatic submission and manage your own transactions:

To control transactions and when changes are applied to the database. It takes a single SQL statement or a group of SQL statements as a logical unit, and if any statement fails, the whole transaction fails.

To enable manual transaction support using auto commit mode instead of the jdbc driver default, use the setautocommit () method of the connection object. If you pass a Boolean value of false to setautocommit(), turn off autocommit. You can reopen it by passing a Boolean value of true.

For example, if there is an object named conn connection, the following code turns off automatic submission:

Commit and rollback once the changes have been completed, submit changes, then call commit (in connection objects) method, as shown below:

Otherwise, rollback the database connection conn made by the update, and use the following code:

The following example demonstrates how to use a commit and rollback object:

In this case, without the above insert statement, it will succeed and everything will be rolled back.

Transaction commit and rollback example the following is an example described using transaction commit and rollback.

Based on the environment and database installation, this sample code has been learned in the previous chapters.

Copy the JDBC example in the following example Java, compile and run as follows:

Now let's compile the above example as follows:

When running JDBC example, it produces the following results:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>