事务练习-购买图书
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BookStore {
public static boolean buy(int userid,int bookid) {
String update1="update bookstore set count=count-1 where bookid=?";
String update2="update sys_user set remain=remain-(select price from book where bookid=?) where userid=?";
String query1="select count from bookstore where bookid=?";
String query2="select remain from sys_user where userid=?";
Connection conn=jdbcUtil.getConnection();//jdbcUtil为jdbc连接数据库封装
try(PreparedStatement ps_u1=conn.prepareStatement(update1);
PreparedStatement ps_u2=conn.prepareStatement(update2);
PreparedStatement ps_q1=conn.prepareStatement(query1);
PreparedStatement ps_q2=conn.prepareStatement(query2);
){
conn.setAutoCommit(false);//关闭自动提交
//更新
ps_u1.setInt(1, bookid);
ps_u1.execute();
ps_u2.setInt(1, bookid);
ps_u2.setInt(2,userid);
ps_u2.execute();
//查询
ps_q1.setInt(1, bookid);
ResultSet rs1=ps_q1.executeQuery();
rs1.next();
int store=rs1.getInt(1);
ps_q2.setInt(1, userid);
ResultSet rs2=ps_q1.executeQuery();
rs2.next();
int remain=rs2.getInt(1);
if(remain>0 && store>0) {
conn.commit();
}else {
throw new Exception("库存或余额不足");
}
System.out.println("购买成功,剩余余额"+remain+",库存"+store);
return true;
} catch (Exception e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO: handle exception
}finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
public static void main(String[] args) {
buy(2,1);
}
}
sys_user表
bookstore表
book表