单元测试依赖
junit junit4.12
使用注解只在方法中有效@test,只要加了这个注解的方法据可以运行
package com.sqt.test;
import org.junit.Test;
public class TestJdbc3 {
@Test
public void test(){
System.out.println("sadada");
}
}
jdbc事务
start transaction ;#开启事务 update account set money = money-100 where name = 'A'; update account set money = money+100 where name= 'B'; rollback ;#事务回滚 commit ;#提交事务
快捷键trycatch --ctrl+alt+t
在代码中的应用
package com.sqt.test;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestJdbc3 {
@Test
public void test() {
//1.配置信息
String url ="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username ="root";
String password = "root";
Connection connection =null;
try {
//2.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//3.链接数据库
connection = DriverManager.getConnection(url,username,password);
//4.通知数据库开启事务,false是开启事务,等价于start transaction ;#开启事务
connection.setAutoCommit(false);
//5.编写sql语句
String sql1 = "update account set money = money-100 where name = 'A';";
//6.
connection.prepareStatement(sql1).executeUpdate();
//制造错误
//int i =1/0;
String sql2 = "update account set money = money+100 where name= 'B';";
connection.prepareStatement(sql2).executeUpdate();
//以上俩条sql语句都提交成功了提交事务
connection.commit();
System.out.println("执行成功");
} catch (ClassNotFoundException | SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}



