<%@page import="java.sql.*"%>
<%
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "permission";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "zouhuiying";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(false);// Disables auto-commit.
String sql1 = "insert into users(name,userid) VAlUES('aa','1')";
String sql2 = "insert into users(name,userid) VAlUES('bb','2')";
String sql3 = "insert into users(name,userid) VAlUES('cc','3')";
String sql4 = "insert into users(name,userid) VAlUES('dd','4')";
PreparedStatement pre = con.prepareStatement(sql1);
pre.executeUpdate();
pre = con.prepareStatement(sql2);
pre.executeUpdate();
pre = con.prepareStatement(sql3);
pre.executeUpdate();
pre = con.prepareStatement(sql4);
pre.executeUpdate();
con.commit();
} catch (SQLException e) {
System.out.println("Exception");
e.printStackTrace();
if(con!=null)
try {
System.out.println("will rollback");
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
con.close();
}
%>
关于commit:当con.setAutoCommit(false)时,每执行一条sql语句时,并不会立即提交,在所有sql语句执行完后commit一起提交。
关于rollback:
当有一条sql语句没有执行成功,则会抛出异常,不会执行commit语句。抛出异常到达rollback语句,则以前执行成功的sql语句也不会提交,所以所有的sql语句都没有执行。