View Single Post
Old 05-10-2004, 02:29 PM   #5 (permalink)
Belisarius
Java fanboy
 
Belisarius's Avatar
 
Join Date: Aug 2003
Posts: 1,161
Belisarius is on a distinguished road
It looks about right, but I might suggest some tips I've learned from doing JDBC stuff.

I'll post two code segments, first my DBConnection class. This contains a little bit of debugging code to help you find out if you have a connection leak, that is where you open a connection but never close it.

Second, it allows you declare the connection without having to worry about catching an SQLException. This is important later on.

Third, it eliminates the need for the creation of Statement objects. Depending on how much code queaking you do, this can be a help or a hinderance. For my purposes, this works fine.

Fourth, it makes sure everything gets closed. Otherwise you need to keep track of everything, and it can be a pain.

Code:
import java.sql.*;
import javax.sql.*;
import java.util.*;

public class DBConnection{
  
  private static int count = 0;
  private static int max = 0;
  private Connection conn;
  private Statement stmt;
  private ResultSet rset;
  
  public DBConnection(){}
  
  public void init() throws SQLException{
    if(conn == null || conn.isClosed()){
      count++;
      // Useful for finding connection leaks.
      if(count > max){
        max = count;
        System.out.println("Max connections: " + max); 
      }
      // Create Connection here.
  }
  
  public ResultSet executeQuery(String query) throws SQLException{
    init();
    stmt = conn.createStatement();
    rset = stmt.executeQuery(query);
    return rset;
  }
  
  public void executeUpdate(String query) throws SQLException{
    init();
    stmt = conn.createStatement();
    stmt.executeUpdate(query);
  }
  
  //
  // ONLY CLOSE WHEN YOU ARE DONE WITH A RESULT SET! 
  //
  
  public void close(){
    if(rset != null){
      try{
        rset.close();
      }catch(SQLException sqle){}
      rset = null;
    }
    if(stmt != null){
      try{
        stmt.close();
      }catch(SQLException sqle){}
      stmt = null;
    }
    if(conn != null){
      try{
        conn.close();
      }catch(SQLException sqle){}
      conn = null;
      count--;
    }
  }
}
__________________
GitS

Last edited by Belisarius; 05-12-2004 at 04:34 AM.
Belisarius is offline   Reply With Quote