• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Would this cause problems closing statements ?

 
Alok Pota
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Transaction {

private List statements;
private Connection conn;
public Transaction(Connection conn) {
this.statements = new ArrayList();
this.conn = conn;
this.conn.setAutoCommit(false);
}
public PrepareStatement prepareStatement(String query) throws SQLException {
PrepareStatement stmt = this.conn.prepareStatement(query);
this.statements.add(stmt);
return stmt;
}
public void execute() throws SQLException {
int count = 0;
for (int i =0; i < statements.size(); ++i) {
PrepareStatement stmt = (PrepareStatement)statements.get(i);
count += stmt.executeUpdate();
}
System.out.println("Updated "+count+" rows ");
}

public void commit() throws SQLException {
try {
this.conn.commit();
} finally {
closeAllStatements();
}
}
public void rollback() throws SQLException {
try {
this.conn.rollback();
} finally {
closeAllStatements();
}
}
private void closeAllStatements() {
try {
for (int i =0; i < statements.size(); ++i) {
PrepareStatement stmt = (PrepareStatement)statements.get(i);
stmt.close();
}
} catch(Exception e) {
//eat?
}
}
}

I have a class like the above. The client calls the public prepareStatement on this object instead of the connection and that way this object keeps track of all the statements its doled out. At the end I hae something like this in the client code
Client call A
~~~~~~~~~~~~~
try {
Transaction tt = new Transaction(conn);
doWork(tt); //Bind parameters to statement;
tt.execute();
tt.commit();
} catch(Exception e) {
tt.rollback();
}
The conn stored in the Transaction class is closed outside the Transaction object (I know thats happening). Given that, is it still possible to have open connections/cursors with the above code? Am i opening execessive statements and not closign them immediatly after creating them?
Note that the entire call A happens in the doPost of a servlet
hence its guaranteed to be executed in one block. I don't see how the above could keep statements open.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic