JDBC编程-事务编程(四)(二)

2015-11-21 01:41:19 · 作者: · 浏览: 7
eption{ String sql = "INSERT INTO tbl_user(id,name,password,email)" + "VALUES(10,'Tom','123456','tom@qq.com')"; Statement st = (Statement) 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 = (Statement) conn.createStatement(); int count = st.executeUpdate(sql); System.out.println("插入了"+count+"行地址数据"); } public static void main(String[] args) { Connection conn = null; try { conn = getConnection(); conn.setAutoCommit(false); insertUserData(conn); insertAddressData(conn); conn.commit(); } catch (SQLException e) { System.out.println("==========捕获SQL异常========="); e.printStackTrace(); try { conn.rollback(); System.out.println("=======s事务回滚成功======="); } catch (Exception e2) { e2.printStackTrace(); } }finally{ try { if (conn != null) { conn.close(); } } catch (Exception e3) { e3.printStackTrace(); } } }

Console界面的报错信息为:

插入了1行用户数据 ==========捕获SQL异常========= com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '10')' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) at com.mysql.jdbc.Util.getInstance(Util.java:360) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:978) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2526) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1618) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1549) at liu.peng.jdbc.TransactionTest.insertAddressData(TransactionTest.java:31) at liu.peng.jdbc.TransactionTest.main(TransactionTest.java:40) =======s事务回滚成功=======

证明两条数据都没有插入进去保证了数据的完整性,而第一次只是插入user表的数据,没有插入address表数据,造成数据不完整。