Could you please post complete code that you want to discuss? Without that, it is difficult to figure out the changes you are trying to make to code that is given with the question.
Assuming that the table student2 does not have any row, how many rows will be present in this table after the following code is executed?
try (Connection c = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app");){
c.setAutoCommit(false);
Statement stmt = c.createStatement();
int a1 = stmt.executeUpdate("insert into STUDENT2 values (1, 'aaa', 1.1)");
Savepoint sp1 = c.setSavepoint();
int a2 = stmt.executeUpdate("insert into STUDENT2 values (2, 'bbb', 2.1)");
******c.rollback(sp1);***** <--- pass sp1 to rollback
int a3 = stmt.executeUpdate("insert into STUDENT2 values (3, 'ccc', 3.1)");
c.setAutoCommit(true);
int a4 = stmt.executeUpdate("insert into STUDENT2 values (4, 'ddd', 4.1)");
}catch (SQLException e){
e.printStackTrace();
}
Last edited by admin on Tue Apr 19, 2016 3:22 am, edited 3 times in total.
Reason:Updated the code to show the change
Assuming that you are trying to change the code as shown above, the call to rollback will roll back the row inserted by int a2 = stmt.executeUpdate("insert into STUDENT2 values (2, 'bbb', 2.1)");
So finally, the table should have records for 1, 3, and 4.
admin wrote:Assuming that you are trying to change the code as shown above, the call to rollback will roll back the row inserted by int a2 = stmt.executeUpdate("insert into STUDENT2 values (2, 'bbb', 2.1)");
So finally, the table should have records for 1, 3, and 4.
An insert query tries to insert a new row and if a row by the same pk exists, the db will reject the query and you will end up with an SQLException in the java code.
You can try it out with JavaDB that comes bundled with IDEs such as NetBeans.