导包
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
Junit单元测试
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行。(import org.junit.Test)
事务
只有当所有事务都正确,才提交事务,数据库才发生相应变动,保证了数据操作的安全。
1.
1.
1. 开启事务
//通知数据库开启事务,false 开启
connection.setAutoCommit(false);
2. 2. 2. 事务提交
connection.commit();
3. 3. 3. 事务回滚
//如果出现异常,就通知数据库回滚事务
connection.rollback();
4. 4. 4. 关闭事务
connection.close();
实例(银行转账)
1.
1.
1. 使用1/0表达式来制造错误;
2.
2.
2. 不开启事务,转账失败且无法回滚,即双方都损失了转账的钱;
3.
3.
3. 开启事务,则通过try-catch回滚,双方转账失败,保持了原先的状态。
package com.tl.study01;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @author tl
* 事务 回滚 Junit单元测试
*/
public class TestJdbc04 {
@Test
public void test() {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc_study?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123";
Connection connection = null;
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);
//3.通知数据库开启事务,false 开启
connection.setAutoCommit(false);
String sql = "update account set money = money-100 where name = 'A'";
connection.prepareStatement(sql).executeUpdate();
//制造错误
int i = 1/0;
String sql2 = "update account set money = money+100 where name = 'B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//以上两条SQL都执行成功了,就提交事务!
System.out.println("success");
} catch (Exception e) {
try {
//如果出现异常,就通知数据库回滚事务
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}