Problem with Transaction rollback with JDBC (mysql)
843854Feb 24 2005 — edited Nov 20 2014I have written an example program to see if the transaction rollback is properly working or not. I am using mysql database. I turned autocommit mode to false and then explicitly rollbacked transaction :- problem i faced is
Create stament gets executed but insert statement is rollbacked only. But, I think that both should be rollbacked,can someone help me as I am not able to figure out the problem. Here is the complete code :
import java.sql.*;
public class CreateCoffees {
public static void main(String args[]) {
String url = "jdbc:mysql://localhost/test";
Connection con = null;
String createString;
createString = "create table COFFEES " +
"(COF_NAME varchar(32), " +
"SUP_ID int, " +
"PRICE float, " +
"SALES int, " +
"TOTAL int)";
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"root", "root");
// Set Autocommit false
con.setAutoCommit(false);
stmt = con.createStatement();
// execute create table statement
stmt.executeUpdate(createString);
System.out.println("Auto commit mode is " + con.getAutoCommit());
// enter an item into the database
stmt.executeUpdate("insert into COFFEES " +
"values('Colombian', 00101, 7.99, 0, 0)");
// rollback complete transaction
con.rollback();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if(con != null) {
con.close();
}
if(stmt != null) {
stmt.close();
}
}catch(SQLException ex) {
ex.printStackTrace();
}
}
}
}
Problem : Coffees table is created but the entry is not inserted into the coffees. But I think both should not be executed as autocommit mode is off. (using mysql 4.1.27)