JDBC默认是自动提交,事务是关闭的,statement|preparedStatement.executeUpdate()或excute()执行增删改,执行一次就提交一次(自动同步到数据库)。

JDBC事务示例:

  //从properties文件中加载数据库配置
Properties properties = new Properties();
InputStream inputStream =Class.forName("test.Test").getResourceAsStream("/mysql.properties");
properties.load(inputStream); String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String pwd=properties.getProperty("password"); Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, pwd);
connection.setAutoCommit(false); //关闭自动提交,此句代码会自动开启事务。默认为true,自动提交。 String sql1 = "insert into student_tb (name,age,score) values (?,?,?)";
PreparedStatement preparedStatement1 = connection.prepareStatement(sql1);
preparedStatement1.setString(1,"chy");
preparedStatement1.setInt(2,20);
preparedStatement1.setInt(3,100);
preparedStatement1.executeUpdate(); //放置到队列中 String sql2 = "update student_tb set name=? where id=?";
PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
preparedStatement2.setString(1,"CoCo");
preparedStatement2.setInt(2,10);
preparedStatement2.executeUpdate(); //放置到队列中 try{
connection.commit(); //提交事务
}catch (SQLException e){
connection.rollback(); //失败就回滚
} finally {
preparedStatement1.close();
preparedStatement2.close();
connection.close();
}

最新文章

  1. F2工作流引擎之 工作流运转模型(三)
  2. iOS内部跳转问题
  3. C++矢量图形库系列(1)——矢量图形库乱谈(转)
  4. 进程间通信之POSIX信号量
  5. IIS设置允许下载.exe文件解决方法(转)
  6. 对于Linux和windows的个人的看法
  7. ubuntu 14.04 chromium 设备adobe flash player(亲测可行)
  8. 【转】基于RSA算法实现软件注册码原理初讨
  9. 纯Python综合图像处理小工具(1)分通道直方图
  10. Python 协程总结
  11. ES6 let和const命令(3)
  12. Scrapy抓取Quotes to Scrape
  13. 带着萌新看springboot源码11(springboot启动原理 源码上)
  14. uwp 动画Storyboard
  15. js 变量作用域
  16. Nifi 老是死机
  17. Sql Server :SELECT a.*,b.HZXM FROM YG_LIS_JCBYTK a(nolock)中的NOLOCK作用
  18. java 堆排序的实现
  19. 简简单单搞掂恼人的Laravel 5安装
  20. TypeScript 照猫画虎

热门文章

  1. cookies , sessionStorage 及 localStorage 的初步的区别
  2. Pandas | 28 与SQL比较
  3. 【数位DP】【P4317】花神的数论题
  4. 【数论&线段树】【P4140】[清华集训2015]奇数国
  5. ORA-01950:对表空间“”XXXX”无权限,解决办法
  6. 【luoguP1382】楼房
  7. E437: terminal capability "cm" required 解决办法
  8. centos git编译
  9. [技术博客]升级 API 面临的问题
  10. JS 中判断数据类型是否为 null、undefined 或 NaN