java當中JDBC當中的transaction例子

[學習筆記]java

7.jdbc的transaction例子:mysql

import java.sql.*;sql

public class MySQlTransaction1 {學習

public static void main(String[] args) throws SQLException {
/*in my sql: create table Accounts(
ID int(4) not null,
NAME varchar(15),
BALANCE int(4),
primary key(ID)
) type=INNODB;
insert into Accounts values(1,'wangwu',100);
insert into Accounts values(3,'zhangsan',300);
insert into Accounts values(4,'lisi',400);
*/
Connection con = null;
Statement s = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "1234");
//s = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
/*by default, whenever execute a sql, it will commit automatically,
public void setAutoCommit(boolean autoCommit) throws SQLException
Sets this connection's auto-commit mode to the given state. If a connection is in auto-commit
mode, then all its SQL statements will be executed and committed as individual transactions.
Otherwise, its SQL statements are grouped into transactions that are terminated by a call to
either the method commit or the method rollback. By default, new connections are in
auto-commit mode. */this

s = con.createStatement();spa

s.executeUpdate("update ACCOUNTS set BALANCE=508 where ID=3");
System.out.println("333333");
/*下一步中原本應爲where ID=4, 可是卻誤寫成了www ID=4, 因此有錯,因此到catch中,但rollback時
, 卻作不成功, 由於是autocommited模式,因此上一句ID=3,就作真改爲508了。*/
s.executeUpdate("update ACCOUNTS set BALANCE=608 www ID=4");
System.out.println("444444");.net

System.out.println("con = " + con);
}
catch (Exception e) {
try{
con.rollback();
System.out.println("rollback successfully");
}catch (Exception ex)
{
文章轉載自原文:https://blog.csdn.net/qq_43650923/article/details/100653000blog

相關文章
相關標籤/搜索