JDBC - Transaction
Posted pp_crz_coder
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC - Transaction相关的知识,希望对你有一定的参考价值。
Transaction: a bunch of operation in logic, the unit which consists the operation will works all or breaks down all.
Every operation of mysql server is a independent transaction in default situation.
TPL(Transaction Processing Language):
start transaction
commit
rollback
SQL statement:
CREATE TABLE account( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40), money FLOAT ); INSERT INTO account(name,money) VALUES(‘aa‘,1000); INSERT INTO account(name,money) VALUES(‘aa‘,1000); INSERT INTO account(name,money) VALUES(‘aa‘,1000); START TRANSACTION; UPDATE account SET money=money-100 WHERE name=‘aa‘; UPDATE account SET money=money+100 WHERE name=‘bb‘; COMMIT;
JDBC code:
package com.pp.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import org.junit.Test; import com.pp.util.JdbcUtil; public class TransactionDemo { @Test public void test1() { Connection connection = null; PreparedStatement pstatement = null; try { connection = JdbcUtil.getConnection(); // start transaction connection.setAutoCommit(false); pstatement = connection .prepareStatement("UPDATE accout SET money=money-100 WHERE name=‘aa‘"); pstatement.executeUpdate(); pstatement = connection .prepareStatement("UPDATE accout SET money=money-100 WHERE name=‘aa‘"); pstatement.executeUpdate(); // commit connection.commit(); } catch (Exception e) { e.printStackTrace(); } finally { } } }
以上是关于JDBC - Transaction的主要内容,如果未能解决你的问题,请参考以下文章
mysql 错 Could not open JDBC Connection for transaction; nested exception is java.sql.SQLExceptio(代码片