Utility class

      In computer programming, a utility class is a class that defines a set of methods that perform common, often re-used functions. Most utility classes define these common methods under static (see Static variable) scope. Examples of utility classes include java.util.Collections [1] which provides several utility methods (such as sorting) on objects that implement a Collection (java.util.collection [2] ).

      See also

      DbConnection.java(util class):-
       
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.PreparedStatement;
      import java.sql.SQLException;
       
      public class DbConnection 
      {
       
              public static Connection con;
              public static String uId="User_id";
              public static String pwd="password";
       
              public static Connection createConnection() {
                      try {
                              // loading the driver
                              Class.forName("oracle.jdbc.driver.OracleDriver");
                              // creating a connection
                              String conUrl = "jdbc:oracle:thin:@Host_id:Port:SID";
                              con = DriverManager.getConnection(conUrl,uId, pwd);
                      } catch(ClassNotFoundException e) {
                              System.out.println("driver not found"); 
                      } catch (SQLException sq1ex) {
                              System.out.println("connection exception"+sq1ex);
                      }
       
                      return con;
              }
       
              public static void closeConnection(Connection con) {
                      if(con!=null) {
                              try {
                                      con.close();
                              } catch (SQLException e) {
                                      // TODO Auto-generated catch block
                                      e.printStackTrace();
                              }
                      }
              }
       
              public static void closeStatement(PreparedStatement ps) {
                      if(ps!=null) {
                              try {
                                      ps.close();
                              } catch (SQLException e) {
                                      // TODO Auto-generated catch block
                                      e.printStackTrace();
                              }
                      }
              }
      }
      
      ↑Jump back a section

      External links

      • Utility Pattern: For a utility class, which does not require instantiation and only has static methods, use a private constructor
      ↑Jump back a section
      Last modified on 13 February 2013, at 13:04