DriverManager是驱动的管理类调用配置文件创建Connection对象

/**
* DriverManager是驱动的管理类。
* 1)可以通过重载的getConnection()方法获取数据库连接,而Driver类需要调用Properties,较为方便
* 2)可以同时管理多个驱动程序:若注册了多个数据库连接,则调用getConnection()方法时传入的参数不同,即返回不同的数据库连接
* @throws ClassNotFoundException
* @throws SQLException
* @throws IOException
*/

@Test
public void testGetConnection2() throws ClassNotFoundException, IOException, SQLException{
System.out.println(getConnection2());
}

public Connection getConnection2() throws IOException, ClassNotFoundException, SQLException{
//1、准备连接数据库的4个字符串
//1)创建properties对象
Properties properties=new Properties();
//2)获取jdbc.properties对应的输入流
InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");
//3)加载2)对应的输入流
properties.load(in);
//4)具体决定四个字符串
String url=properties.getProperty("jdbcUrl");
String user=properties.getProperty("user");
String password=properties.getProperty("password");
String driverClass=properties.getProperty("driverClass");
//2、加载数据库驱动程序(对应的Driver实现类中有注册驱动的静态代码块)
Class.forName(driverClass);
//3、通过DriverManager的getConnection()方法获取数据库连接
Connection connection=DriverManager.getConnection(url, user, password);
return connection;
//System.out.println(connection);
//return connection;
}

原文地址:https://www.cnblogs.com/xiaona19841010/p/5192309.html