1. 程式人生 > 其它 >萬能JDBC工具類【DBUtil 】

萬能JDBC工具類【DBUtil 】

package com.jdbc;
import java.sql.*;
import java.util.*;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBUtil {
	public static void main(String[] args) {
	
	//構造方法私有化 防止別人以後欠欠的new本類的物件
	private DBUtil() {}

	private static  DataSource dataSource;
	//要在靜態程式碼塊中載入驅動類
	static {
		dataSource=new ComboPooledDataSource("mysql");
	}
	//得到連線
	public static Connection getConn() {
		Connection conn=null;
		try {
			conn=dataSource.getConnection();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		
		return conn;
	}

	//清理資源
	public static void close(ResultSet rs, Statement stm,Connection conn) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(stm!=null) {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	//清理資源
		public static void close(Connection conn) {
			if(conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	// 萬能更新(可以進行新增,更新,刪除三種操作)
	public static int update(String sql, Object... params) {
		int result = 0;
		QueryRunner qr = new QueryRunner(); // 是一個執行緒不安全的類
		Connection conn=getConn();
		try {
			result = qr.update(conn, sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			close(conn);
		}
		
		return result;
	}

	// 新增資料,並將生成的自增ID返回
	public static int addWithId(String sql, Object... params) {
		int autoId = 0;
		Connection conn = null;
		PreparedStatement stm = null;
		ResultSet rs = null;
		try {
			conn = getConn();
			stm = conn.prepareStatement(sql,
					PreparedStatement.RETURN_GENERATED_KEYS);
			for (int i = 0; i < params.length; i++) {
				stm.setObject(i + 1, params[i]);
			}

			// 執行新增操作
			stm.executeUpdate();

			// 取出生成的自增ID
			ResultSet rsKey = stm.getGeneratedKeys();
			rsKey.next();
			autoId = rsKey.getInt(1);

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			close(rs, stm, conn);
		}
		return autoId;
	}

	// 查詢出一個單個的物件
	public static <T> T getSingleObj(String sql, Class<T> clazz,
			Object... params) {
		QueryRunner qr = new QueryRunner();
		T result = null;
		Connection conn=getConn();
		try {
			result = qr.query(conn, sql, new BeanHandler<T>(clazz),
					params);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			close(conn);
		}

		return result;
	}
	

	// 查詢出物件列表(以ArrayList的方式返回),注意,如果沒有查詢到資料,該方法返回一個空列表,而不是null
	public static <T> List<T> getList(String sql, Class<T> clazz,
			Object... params) {
		List<T> list = new ArrayList<T>();
		QueryRunner qr = new QueryRunner();
		Connection conn =getConn();
		
		try {
			list = qr.query(conn, sql, new BeanListHandler<T>(clazz), params);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally{
			close(conn);
		}

		return list;
	}

	// 返回Map集合(該方法只將一條資料返回為Map集合,key為欄位名稱,value為欄位值)
	public static Map<String, Object> getMap(String sql, Object... params) {
		Map<String, Object> m = null;
		QueryRunner qr = new QueryRunner();
		Connection conn =getConn();
		
		try {
			m = qr.query(conn, sql, new MapHandler(), params);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			close(conn);
		}

		return m;
	}

	// 返回一個List集合,其中每條資料都被封裝成了一個Map集合,
	public static List<Map<String, Object>> getMapList(String sql,
			Object... params) {
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		QueryRunner qr = new QueryRunner();
		Connection conn =getConn();

		try {
			mapList = qr.query(conn, sql, new MapListHandler(),
					params);

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			close(conn);
		}

		return mapList;
	}

	// 返回單行單個數據,該方法可以用來查詢記錄數(這時請使用Long型進行接收),單個欄位值等資料
	public static <T> T getScalar(String sql, Object... obj) {
		T result = null;
		QueryRunner qr = new QueryRunner();
		Connection conn = getConn();
		try {
			result = qr.query(conn, sql, new ScalarHandler<T>(1), obj);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex);
		} finally {
			close(conn);
		}

		return result;
	}
}