JDBC2 --- 获取数据库连接的方式二 --- 技术搬运工(尚硅谷)

/**
  * 方式二,对方式一的迭代
 * 在如下的程序中,不出现第三方的api,使得程序具有更好的可移植性。
 * @throws Exception
 */
@Test
public void testConnection2() throws Exception {
    //1.获取Driver实现类对象,使用反射
    Class<?> clazz = Class.forName("com.mysql.jdbc.Driver");
    Driver driver = (Driver) clazz.newInstance();
    
    //2.提供需要连接的数据库
    String url = "jdbc:mysql://localhost:3306/test";
    
    //3.连接数据库的用户名和密码
    Properties info = new Properties();
    info.setProperty("user", "root");
    info.setProperty("password", "123456");
    
    //4.获取连接
    Connection connection = driver.connect(url, info);
    System.out.println(connection);
}

猜你喜欢

转载自www.cnblogs.com/noyouth/p/11731798.html