工具类的两种存在形式

1,静态类的 方法(final,static,private的构造方法)

package com.xing.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public final class StaticUtils {
	private static String url= "jdbc:mysql://localhost:3306/XingCompany";//协议:自协议//[ip]:[port]/database
	private static String user = "root";
	private static String password = "";
	
	private StaticUtils(){
		
	}
	
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(url, user, password);
	}
	
	public static void free(Connection conn, Statement statement, ResultSet rs){
		try {
			if (rs != null){
				rs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if (statement != null){					
					statement.close();
					}
			} catch (SQLException e) {
					e.printStackTrace();					
			} finally {
				if (conn != null){
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
			
		}
	}
	
}

  2. 采用单例的方式(注意采用一个private static的变量封装ins,然后通过一个public static的方法公布出来,注意ins的预初始化。。。)

package com.xing.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public final class SingletonUtil {
	private String url= "jdbc:mysql://localhost:3306/XingCompany";//协议:自协议//[ip]:[port]/database
	private String user = "root";
	private String password = "";
	
	private SingletonUtil(){
		
	}
	
	private static SingletonUtil ins = new SingletonUtil();
	
	public static SingletonUtil getInstance(){
		return ins;
	}
	
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public Connection getConnection() throws SQLException{
		return DriverManager.getConnection(url, user, password);
	}
	
	public void free(Connection conn, Statement statement, ResultSet rs){
		try {
			if (rs != null){
				rs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if (statement != null){					
					statement.close();
					}
			} catch (SQLException e) {
					e.printStackTrace();					
			} finally {
				if (conn != null){
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
			
		}
	}
	
}

  

posted on 2013-02-18 11:37  要强小伙  阅读(155)  评论(0编辑  收藏  举报