通过资源文件获取连接的JDBC数据库连接类

连接数据库的工具类:

 

package com.zlk.dao;

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

import com.zlk.util.EnvironmentConfig;

public class DBConnection {
	private static DBConnection conn = null; 
	private static String DB_PROPERTIES="/com/zlk/config/db.properties";
	private static EnvironmentConfig ec = EnvironmentConfig.getInstance();
	
	private static String DRIVER_CLASS_NAME = ec.getPropertyValue(DB_PROPERTIES, "db.jdbc.driverClassName");
	private static String URL = ec.getPropertyValue(DB_PROPERTIES, "db.jdbc.url");
	private static String USERNAME = ec.getPropertyValue(DB_PROPERTIES, "db.jdbc.username");
	private static String PASSWORD= ec.getPropertyValue(DB_PROPERTIES, "db.jdbc.password");
	
	/**
	 * 私有构造函数,加载连接驱动
	 */
	private DBConnection(){
		try {
			Class.forName(DRIVER_CLASS_NAME);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("连接驱动未找到..............");
			e.printStackTrace();
		}
	}
	
	/**
	 * 实例化类对象
	 */
	public static DBConnection getInstance(){
		if(conn == null){
			return new DBConnection();
		}
		return conn;
	}
	
	/**
	 * 创建数据库连接
	 */
	public Connection getConnection() throws SQLException{
		return DriverManager.getConnection(URL,USERNAME,PASSWORD);
	}
	
	/**
	 * 释放资源
	 */
    public void release(Connection conn, PreparedStatement ps,ResultSet rs) {   
        if (rs != null)try {rs.close();} catch (SQLException e) {e.printStackTrace();}   
        if (ps != null) try {ps.close();} catch (SQLException e) {e.printStackTrace();}   
        if (conn!= null)try {conn.close();} catch (SQLException e) {e.printStackTrace();}   
    }   
  
	/**
	 * 释放资源
	 */
    public void release(Object obj) {   
        if (obj instanceof Connection) {   
            Connection conn = (Connection) obj;   
            if (conn != null)   
                try {   
                    conn.close();   
                } catch (SQLException e) {   
                    e.printStackTrace();   
                }   
        }   
        if (obj instanceof PreparedStatement) {   
            PreparedStatement ps = (PreparedStatement) obj;   
            if (ps != null)   
                try {   
                    ps.close();   
                } catch (SQLException e) {   
                    e.printStackTrace();   
                }   
        }   
        if (obj instanceof ResultSet) {   
            ResultSet rs = (ResultSet) obj;   
            if (rs != null)   
                try {   
                    rs.close();   
                } catch (SQLException e) {   
                    e.printStackTrace();   
                }   
        }   
    }   

}

 

读取资源文件的工具类:

package com.zlk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Properties;

/**  
 * java 读取配置(属性)文件    
 * @author Billows.Van   
 * [email protected]  
 */  
public class EnvironmentConfig {   
    static EnvironmentConfig ec;// 创建对象ec   
    private static Hashtable<String, Properties> register = new Hashtable<String, Properties>();// 静态对象初始化[在其它对象之前]   
  
    private EnvironmentConfig() {   
        super();   
    }   
  
    /**  
     * 取得EnvironmentConfig的一个实例  
     */  
    public static EnvironmentConfig getInstance() {   
        if (ec == null)   
            ec = new EnvironmentConfig();// 创建EnvironmentConfig对象   
        return ec;// 返回EnvironmentConfig对象   
    }   
  
    /**  
     * 读取配置文件  
     */  
    public Properties getProperties(String fileName) {// 传递配置文件路径   
        InputStream is = null;// 定义输入流is   
        Properties p = null;   
        try {   
            p = (Properties) register.get(fileName);// 将fileName存于一个HashTable   
            /**  
             * 如果为空就尝试输入进文件  
             */  
            if (p == null) {   
                try {   
                    is = new FileInputStream(fileName);// 创建输入流   
                } catch (Exception e) {   
                    if (fileName.startsWith("/")) 
                        // 用getResourceAsStream()方法用于定位并打开外部文件。   
                        is = EnvironmentConfig.class.getResourceAsStream(fileName);   
                    else  
                        is = EnvironmentConfig.class.getResourceAsStream("/"+fileName); 
                }   
                p = new Properties();   
                p.load(is);// 加载输入流   
                register.put(fileName, p);// 将其存放于HashTable缓存   
                is.close();// 关闭输入流   
            }   
        } catch (Exception e) {   
            e.printStackTrace(System.out);   
        }   
        return p;// 返回Properties对象   
    }   
  
    /**  
     * 此处插入方法描述。  
     */  
    public String getPropertyValue(String fileName, String strKey) {   
        Properties p = getProperties(fileName);   
        try {   
            return (String) p.getProperty(strKey);   
        } catch (Exception e) {   
            e.printStackTrace(System.out);   
        }   
        return null;   
    }  
    
    /**
     * 修改配置文件的值
     */
    public void setPropertyValue(String fileName,String strKey,String StrValue){
    	Properties p = getProperties(fileName);
    	OutputStream os = null;
    	try {
    		if(p!=null){
			  File file = new File(this.getClass().getResource("/").getPath().replace("%20", " "));//找到指定目录,其中路径中的“%20”用空格代替
			  file = new File(file.getPath()+fileName);//找到指定文件
			  
			  os = new FileOutputStream(file);
			  p.setProperty(strKey, StrValue);
			  p.store(os, "Last Modified");
    		}
		} catch (Exception e) {
			e.printStackTrace(System.out);   
		}finally{
			try {
				os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    }
    
    /**
     * 重载资源文件
     */
    public void reloadProterties(){
    	this.register.clear();
    }
}  

 

资源文件:

db.jdbc.driverClassName=com.microsoft.jdbc.sqlserver.SQLServerDriver
db.jdbc.url=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test
db.jdbc.username=sa
db.jdbc.password=sa

 

你可能感兴趣的:(java,sql,jdbc,OS,Microsoft)