JdbcUtils 小工具

// 第一版
    // src 目录下 dbconfig.properties 配置文件, 用来配置四大参数
    // 注意 properties 配置文件中没有分号结尾, 也没有引号
    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mydb1
    username=root
    password=root

    // JdbcUtils 类
    public class JdbcUtils{

        public static Connection getConnection()
                throws IOException, ClassNotFoudException,SQLException{

            // 加载配置文件    
            // 因为配置文件在 src 目录下
            InputStream in = JdbcUtils.class.getClassLoader()
                                .getResourceAsStream("dbconfig.properties");

            // 使用 properties 集合的 load() 方法,
            // 将输入流中的内容加载到 properties 集合中
            Properties props = new Properties();
            props.load(in);                                     

            // 加载驱动类
            Class.forName(props.getProperty("driverClassName"));

            // 获取 Connection 对象

            return DriverManager.getConnection(
                        props.getProperty("url"),
                        props.getProperty("username"),
                        props.getProperty("password")
                    );
        }
    }


// 第一次升级
// 如果两次调用 JdbcUtils.getConnection() 方法,需要加载两次配置文件.
// 驱动类也需要执行多次. 而实际上, 配置文件和驱动类只需要加载一次即可

    public class JdbcUtils{

        private static Properties props = null;

        // 静态代码块, 只在 JdbcUtils 加载时, 执行一次该代码块
        static{
            // 给 props 进行初始化, 即加载 dbconfig.properties 配置文件到 props 对象中
            try{
                InputStream in = JdbcUtils.class.getClassLoader()
                                           .getResourceAsStream("dbconfig.properties");
                props = new Properties();
                props.load(in);

            }catch(IOException e){
                throw new RuntimeException(e);
            }

            // 加载驱动类
            try{
                Class.forName(props.getProperty("driverClassName"));
            }catch(ClassNotFoundException e){
                throw new RuntimeException(e);
            }
        }

        // 获取 Connection 对象
        public static Connection getConnection() throws SQLException{

            return DriverManager.getConnection(
                    props.getProperty("url"),
                    props.getProperty("username"),
                    props.getProperty("password")
            );
        }
    }


// 第二版: 使用 c3p0 连接池获取连接对象

    public class JdbcUtils {
        // 使用的是配置文件的默认配置, 要求在 src 目录下给出 c3p0-config.xml

        private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

        // 使用连接池获取连接对象
        public static Connection getConnection() throws SQLException{
            return dataSource.getConnection();
        }

        // 返回连接池对象
        public static DataSource getDataSource(){
            return dataSource;
        }
    }

参考资料:

原文地址:https://www.cnblogs.com/linkworld/p/7618254.html