Java JDBC事务
2024-10-19 18:41:10
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();
}
最新文章
- F2工作流引擎之 工作流运转模型(三)
- iOS内部跳转问题
- C++矢量图形库系列(1)——矢量图形库乱谈(转)
- 进程间通信之POSIX信号量
- IIS设置允许下载.exe文件解决方法(转)
- 对于Linux和windows的个人的看法
- ubuntu 14.04 chromium 设备adobe flash player(亲测可行)
- 【转】基于RSA算法实现软件注册码原理初讨
- 纯Python综合图像处理小工具(1)分通道直方图
- Python 协程总结
- ES6 let和const命令(3)
- Scrapy抓取Quotes to Scrape
- 带着萌新看springboot源码11(springboot启动原理 源码上)
- uwp 动画Storyboard
- js 变量作用域
- Nifi 老是死机
- Sql Server :SELECT a.*,b.HZXM FROM YG_LIS_JCBYTK a(nolock)中的NOLOCK作用
- java 堆排序的实现
- 简简单单搞掂恼人的Laravel 5安装
- TypeScript 照猫画虎
热门文章
- cookies , sessionStorage 及 localStorage 的初步的区别
- Pandas | 28 与SQL比较
- 【数位DP】【P4317】花神的数论题
- 【数论&;线段树】【P4140】[清华集训2015]奇数国
- ORA-01950:对表空间“”XXXX”无权限,解决办法
- 【luoguP1382】楼房
- E437: terminal capability "cm" required 解决办法
- centos git编译
- [技术博客]升级 API 面临的问题
- JS 中判断数据类型是否为 null、undefined 或 NaN