1. 程式人生 > >簡單的資料庫連線工具類DBUtil

簡單的資料庫連線工具類DBUtil



import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtils {

	//利用Properties類讀取properties配置檔案
	private static Properties prop = new Properties();
	
	static{
		InputStream in = null;
		//利用類載入器去獲取資源
		in = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
		try{
			prop.load(in);//從輸入流中讀取屬性列表(鍵和元素對)。
			Class.forName(prop.getProperty("driver"));//載入驅動
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(in != null){//判斷是否為空才關閉資源
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 獲取連線
	 * @return
	 */
	public static Connection getConnection(){
		Connection conn =  null;
		try {
			conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 執行編譯
	 * @param conn
	 * @param sql
	 * @return
	 */
	public static PreparedStatement getPreparedStatement(Connection conn,String sql){
		PreparedStatement stmt = null;	//定義一個預編譯物件
		try {
			stmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}
	
	/**
	 * 釋放資源
	 * @param conn
	 * @param stm
	 * @param rs
	 */
	public static void releaseResource(Connection conn,Statement stm,ResultSet rs){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				rs = null;
				if(stm != null){
					try {
						stm.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}finally{
						stm = null;
						if(conn != null){
							try {
								conn.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
	
}