JDBC默认是自动提交,事务是关闭的,statement|preparedStatement.executeUpdate()或excute()执行增删改,执行一次就提交一次(自动同步到数据库)。
JDBC事务示例:
1 //从properties文件中加载数据库配置 2 Properties properties = new Properties(); 3 InputStream inputStream =Class.forName("test.Test").getResourceAsStream("/mysql.properties"); 4 properties.load(inputStream); 5 6 String driver = properties.getProperty("driver"); 7 String url = properties.getProperty("url"); 8 String user = properties.getProperty("user"); 9 String pwd=properties.getProperty("password"); 10 11 Class.forName(driver); 12 Connection connection = DriverManager.getConnection(url, user, pwd); 13 connection.setAutoCommit(false); //关闭自动提交,此句代码会自动开启事务。默认为true,自动提交。 14 15 String sql1 = "insert into student_tb (name,age,score) values (?,?,?)"; 16 PreparedStatement preparedStatement1 = connection.prepareStatement(sql1); 17 preparedStatement1.setString(1,"chy"); 18 preparedStatement1.setInt(2,20); 19 preparedStatement1.setInt(3,100); 20 preparedStatement1.executeUpdate(); //放置到队列中 21 22 String sql2 = "update student_tb set name=? where id=?"; 23 PreparedStatement preparedStatement2 = connection.prepareStatement(sql2); 24 preparedStatement2.setString(1,"CoCo"); 25 preparedStatement2.setInt(2,10); 26 preparedStatement2.executeUpdate(); //放置到队列中 27 28 try{ 29 connection.commit(); //提交事务 30 }catch (SQLException e){ 31 connection.rollback(); //失败就回滚 32 } finally { 33 preparedStatement1.close(); 34 preparedStatement2.close(); 35 connection.close(); 36 }