标签:
package jdbcstu; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class TransactionTest { public static void main(String[] args) { Connection conn=null; try { conn=getConnection(); conn.setAutoCommit(false);//禁止事务的自动提交 insertUserData(conn); insertAddressData(conn); } catch (SQLException e) { System.out.println("======捕获到SQL异常===="); e.printStackTrace(); try { conn.rollback(); System.out.println("===事务回滚成功====="); } catch (Exception e2) { // TODO: handle exception } }finally{ try { if(conn!=null){ conn.close(); } } catch (Exception e3) { e3.printStackTrace(); } } } public static Connection getConnection(){ Connection conn=null; try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db","root",""); } catch (Exception e) { // TODO: handle exception } return conn; } public static void insertUserData(Connection conn) throws SQLException { String sql="insert into tbl_user(id,name,password,email)"+ "values(10,‘Tom‘,‘123456‘,‘tom@gmail.com‘)"; Statement st=conn.createStatement(); int count=st.executeUpdate(sql); System.out.println("向用户表中插入了"+count+"条记录"); } public static void insertAddressData(Connection conn) throws SQLException { String sql="insert into tbl_address(id,city,country,user_id)"+ "values(1,‘shanghai‘,‘china‘,‘10‘)"; Statement st=conn.createStatement(); int count=st.executeUpdate(sql); System.out.println("向地址表中插入了"+count+"条记录"); } }
标签:
原文地址:http://my.oschina.net/u/2356966/blog/413041