Java_jdbc 基础笔记之二 数据库连接

/**
 * DriverManager 类是驱动程序管理器类 
 * 1)可以通过重载的getConnection()方法获取数据库的连接,较为方便
 * 2)可以同时管理多个驱动程序:若注册了多个数据库连接, 则调用getConnection()方法时传入的参数不同, 则返回不同的数据库的连接;
 * 
 * @throws Exception
 * 
 * @throws Exception
 * /
@Test
    public void testDriverManager() throws Exception {
        // 1 准备连接数据库的4个字符串。
        // 驱动的全类名
        String driverClass = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String password = "admin";
        String driverClass1 = "oracle.jdbc.driver.OracleDriver";
        String url1 = "jdbc:oracle:thin:@localhost:1521:orcl";
        String user1 = "scott";
        String password1 = "tiger";

        // 2 加载数据库的驱动程序(对应的Driver 实现类中有注册驱动的静态代码块)
        Class.forName(driverClass1);
        // 3 通过DriverManager的getConnection()方法获取数据库的连接。
        Connection connection = DriverManager.getConnection(url1, user1,
                password1);
        System.out.println(connection);
    }


// 将其封装为方法
    public Connection getConnection1() throws  Exception {
        // 1、首先 准备连接数据库的4个字符串
        String driverClass = null;
        String urljdbc = null;
        String user = null;
        String password = null;
        // 2、读取配置文件
        InputStream is = getClass().getClassLoader().getResourceAsStream(
                "jdbc.properties");
        Properties properties = new Properties();
        // 加载
        properties.load(is);
        driverClass=properties.getProperty("driver");
        urljdbc=properties.getProperty("urljdbc");
        user=properties.getProperty("user");
        password=properties.getProperty("password");
        //3、加载数据库的驱动程序(对应的Driver 实现类中有注册驱动的静态代码块)
        Class.forName(driverClass).newInstance();
        // 4 通过DriverManager的getConnection()方法获取数据库的连接。
        Connection conn=DriverManager.getConnection(urljdbc, user, password);
        return conn;
    }
    @Test
    public void testConnection1() throws Exception{
        System.out.println(getConnection1());

    }
}

转 : https://blog.csdn.net/YL1214012127/article/details/48211415

原文地址:https://www.cnblogs.com/fps2tao/p/12023242.html