import java.sql.*;
public class TestTransaction ...{

public static void main(String[] args) ...{
Connection conn = null;
Statement stmt = null;

try ...{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/data?user=root&password=123456";
conn = DriverManager.getConnection(url);
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.addBatch("insert into user values (3, 'aaa', 'aaa')");
stmt.addBatch("insert into user values (4, 'bbb', 'bbb')");
stmt.addBatch("insert into user values (5, 'ccc', 'ccc')");
stmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);
} catch (ClassNotFoundException e) ...{
e.printStackTrace();
} catch(SQLException e) ...{
e.printStackTrace();

try ...{
if(conn != null)
...{
conn.rollback();
conn.setAutoCommit(true);
}
} catch (SQLException e1) ...{
e1.printStackTrace();
}
}finally ...{
try ...{
if(stmt != null)
stmt.close();
if(conn != null)
conn.close();
} catch (SQLException e) ...{
e.printStackTrace();
}
}

}
}
1368

被折叠的 条评论
为什么被折叠?



