java当中JDBC当中的transaction例子
[学习笔记]
7.jdbc的transaction例子:
import java.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. */
s = con.createstatement();
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");
system.out.println("con = " + con);
}
catch (exception e) {
try{
con.rollback();
system.out.println("rollback successfully");
}catch (exception ex)
{
ex.printstacktrace();
}
}
finally {
s.close();
con.close();
system.out.println("successfully in finally");
}
}
}
文章转载自原文:
上一篇: 交换排序
推荐阅读
-
java当中JDBC当中的transaction例子
-
java当中JDBC当中请给出一个Oracle DataSource and SingleTon例子
-
java当中JDBC当中请给出一个sql server的dataSource的helloworld例子
-
java当中JDBC当中请给出一个SQLServer DataSource and SingleTon例子
-
第51节:Java当中的集合框架Map
-
java当中请给出一个oracle的helloworld例子
-
第50节:Java的当中的泛型
-
第44节:Java当中的JVM
-
java当中JDBC当中请给出一个sql server的stored procedure例子
-
在Java当中,如果有一个**类**专门用来存放其它类的对象,这个类就叫做容器