利用jdbc做一个购买的事务
有一个在线交易电商平台,有两张表,分别是库存表和订单表,如下:
现在买家XiaoMing在该平台购买bag一个,需要同时在库存表中对bag库存记录减一,同时在订单表中生成该订单的相关记录。
请编写Java程序,实现XiaoMing购买bag逻辑。订单表ID字段为自增字段,无需赋值。
1 package chatroom; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 10 import javax.imageio.spi.IIOServiceProvider; 11 12 import org.apache.commons.dbcp2.BasicDataSource; 13 14 /** 15 * @author 神余健芝 16 * @date 创建时间:2017年5月20日 下午9:48:47 17 */ 18 public class JDBCTest { 19 public static BasicDataSource ds = null; 20 21 public final static String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 22 public final static String USER_NAME = "root"; 23 public final static String PASSWORD = "123456"; 24 public final static String DB_URL = "jdbc:mysql://localhost/shen_db?useUnicode=true&characterEncoding=utf-8&useSSL=false"; 25 26 public static void dbcpInit() { 27 ds = new BasicDataSource(); 28 ds.setUrl(DB_URL); 29 ds.setDriverClassName(JDBC_DRIVER); 30 ds.setUsername(USER_NAME); 31 ds.setPassword(PASSWORD); 32 } 33 34 public static void tranferAccount() throws ClassNotFoundException { 35 Connection connection = null; 36 PreparedStatement preparedStatement1 = null, preparedStatement2 = null; 37 38 try { 39 connection = ds.getConnection(); 40 System.out.println(connection); 41 connection.setAutoCommit(false); 42 preparedStatement1 = connection.prepareStatement("update inventory set Inventory= ? where ProductName= ?"); 43 preparedStatement1.setInt(1, 19); 44 preparedStatement1.setString(2, "bag"); 45 preparedStatement1.execute(); 46 47 preparedStatement2 = connection.prepareStatement("insert into `Order` (buyer,ProductName) values(?,?)"); 48 preparedStatement2.setString(1, "XiaoMing"); 49 preparedStatement2.setString(2, "bag"); 50 preparedStatement2.execute(); 51 System.out.println(preparedStatement2); 52 53 connection.commit(); 54 } catch (SQLException e) { 55 if (connection != null) 56 try { 57 connection.rollback(); 58 } catch (Exception e2) { 59 e2.printStackTrace(); 60 } 61 } finally { 62 try { 63 if (connection != null) 64 connection.close(); 65 if (preparedStatement1 != null) 66 preparedStatement1.close(); 67 if (preparedStatement2 != null) 68 preparedStatement2.close(); 69 } catch (SQLException e2) { 70 e2.printStackTrace(); 71 } 72 } 73 } 74 75 public static void main(String[] args) throws ClassNotFoundException { 76 dbcpInit(); 77 tranferAccount(); 78 } 79 }