import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Test {
@org.junit.Test
public void show() throws ClassNotFoundException, SQLException {
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String username="root";
String password="123456";
Class.forName("com.mysql.jdbc.Driver");
Connection connection=null;
try {
connection = DriverManager.getConnection(url,username,password);
connection.setAutoCommit(false);
String sql="update `account` SET `money`=money+300 where `name`='A'";
connection.prepareStatement(sql).executeUpdate();
// int i=1/0;
String sql2="update `account` SET `money`=money-300 where `name`='B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();
System.out.println("success");
}catch (Exception e){
try {
connection.rollback();
System.out.print("转账失败");
}catch (Exception e1){
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
最后修改:2020 年 11 月 02 日
© 允许规范转载