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 which provides several utility methods (such as sorting) on objects that implement a Collection (java.util.Collection ).

Example

DbConnection.java(util class):-

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public final class DbConnection {
	public static Connection con;
	public static String uId = "User_id";
	public static String pwd = "password";

	private DbConnection() {
		// Utility classes should always be final and have a private constructor
	}

	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 a catch block
				e.printStackTrace();
			}
		}
	}
}

See also

External links

This article is issued from Wikipedia - version of the 12/18/2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.