JDBC中处理事务(SXT)

 JDBC中处理事务(SXT)

 

Demo

  1. import java.sql.*;
  2. public class TestTransaction
  3. {
  4.     /**
  5.      * @JDBC中处理事务
  6.      */
  7.     public static void main(String[] args)
  8.     {
  9.         // 1.不用PreparedStatement
  10.         Connection conn = null;
  11.         Statement stmt = null;
  12.         String url = "jdbc:mysql://localhost:3306/college";
  13.         String user = "root";
  14.         String password = "123456";
  15.         try
  16.         {
  17.             Class.forName("com.mysql.jdbc.Driver");
  18.             conn = DriverManager.getConnection(url, user, password);
  19.             conn.setAutoCommit(false);
  20.             stmt = conn.createStatement();
  21.             stmt.addBatch("insert into user values(301,'go1','123','0')");
  22.             stmt.addBatch("insert into user values(302,'go2','1234','00')");
  23.             stmt.addBatch("insert into user values(303,'go3','12345','000')");
  24.             stmt.executeBatch();
  25.             conn.commit();
  26.             conn.setAutoCommit(true);
  27.         } catch (ClassNotFoundException e)
  28.         {
  29.             // TODO Auto-generated catch block
  30.             e.printStackTrace();
  31.         } catch (SQLException e)
  32.         {
  33.             e.printStackTrace();
  34.             try
  35.             {
  36.                 if (conn != null)
  37.                 {
  38.                     conn.rollback();
  39.                     conn.setAutoCommit(true);
  40.                 }
  41.             } catch (SQLException e1)
  42.             {
  43.                 // TODO Auto-generated catch block
  44.                 e1.printStackTrace();
  45.             }
  46.         } finally
  47.         {
  48.             try
  49.             {
  50.                 if (stmt != null)
  51.                 {
  52.                     stmt.close();
  53.                     stmt = null;
  54.                 }
  55.                 if (conn != null)
  56.                 {
  57.                     conn.close();
  58.                     conn = null;
  59.                 }
  60.             } catch (SQLException e)
  61.             {
  62.                 // TODO Auto-generated catch block
  63.                 e.printStackTrace();
  64.             }
  65.         }
  66.     }
  67. }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值