以解耦方式连接数据库-通过读取配置文件

package utils.jdbc;

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.util.Properties;


public class DBUtils {

    private Connection conn;
    /**
     * 通过读类路径下的utils.properties 的参数来设置数据库的类型
     * @return conn 返回一个连接
     * @throws IOException 抛出一个IO异常
     * @author 施杰灵
     * 时间:2015年12月7日 
     */
    
    public Connection getConnection() throws IOException{
        /*
         *声明四个参数,分别为
         *数据库驱动
         *JDBC
         *数据库用户名
         *数据库密码 
         */
        String driver = null;
        String url = null;
        String username = null;
        String password = null;
        
        //读取配置文件  以输入流的方式
        InputStream in = getClass().getClassLoader().getResourceAsStream("utils.properties");
        Properties properties = new Properties();
        properties.load(in);  //加载
        /*
         * 从配置文件中读取各个参数的值
         */
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        
        return conn;
    }
    
    public void releaseConn(Connection conn,ResultSet rs,PreparedStatement pstm){
            try {
                if(conn != null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        
        try {
            if(rs != null){
                
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        try {
            if(pstm != null){
                pstm.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }        
    }
}
不为输赢,认真是我的态度
原文地址:https://www.cnblogs.com/meng-xiang/p/5027382.html