class DatabaseConnect
{
Connection conn1, conn2;
//PreparedStatement pstmt1, pstmt2;
public static void main(
String[] args) throws Exception
{
new DatabaseConnect().init();
}
public void init(){
try{
handle();
}
catch(Exception e){
e.printStackTrace();
}
}
public void handle() throws Exception{
try{
System.out.println("***Calling connect()***");
connect();
System.out.println("***Calling doQuery()***");
doQuery();
System.out.println("***Calling doAnotherQuery()***");
doAnotherQuery();
conn1.commit();
}
catch(Exception e){
if(null != conn1) conn1.rollback();
if(null != conn2) conn2.rollback();
throw e;
}
finally{
if(null != conn1) conn1.close();
if(null != conn2) conn2.close();
}
}
public void connect() throws ClassNotFoundException, SQLException{
System.out.println("Connecting to database server ");
Class.forName("com.mysql.jdbc.Driver");
conn1 = DriverManager.getConnection("jdbc:mysql://ip:port/dbName",
"user", "****");
System.out.println("Connection object for DB = "+conn1);
conn1.setAutoCommit(false);
}
public void doQuery() throws SQLException{
PreparedStatement pstmt1 = conn1.prepareStatement("INSERT INTO A VALUES(?, ?, ?, ?, ?)");
PreparedStatement pstmt2 = conn1.prepareStatement("INSERT INTO A VALUES(?, ?, ?, ?, ?)");
pstmt1.setInt(1, 8);
pstmt1.setString(2, "value1");
pstmt1.setString(3, "value1");
pstmt1.setString(4, "value1");
pstmt1.setInt(5, 1);
pstmt2.setInt(1, 9);
pstmt2.setString(2, "value2");
pstmt2.setString(3, "value2");
pstmt2.setString(4, "value2");
pstmt2.setInt(5, 1);
try{
pstmt1.executeUpdate();
pstmt2.executeUpdate();
}
catch(SQLException e){
throw e;
}
finally{
//if(null != pstmt1) pstmt1.close();
//if(null != pstmt2) pstmt2.close();
}
}
public void doAnotherQuery() throws SQLException{
PreparedStatement pstmt1 = conn1.prepareStatement("UPDATE A SET field2 = 'updatevalue' WHERE field = ?");
pstmt1.setString(2, "value");
try{
pstmt1.executeUpdate();
}
catch(SQLException e){
throw e;
}
finally{
//if(null != pstmt1) pstmt1.close();
}
}
}
This is my code. Here even if I comment the prepared statement closing at finnally block, the commit is not working.
What could be the flaw ???