方式一
@Test
public void testConnectionTest1() throws Exception {
//获取驱动
Driver driver = new com.mysql.cj.jdbc.Driver();
//获取配置信息
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "root");
//获取连接
Connection connection = driver.connect(url, info);
System.out.println(connection);
}
~缺点: 对外暴露过多,属于硬编码,移植性差
方式二
public void testConnectionTest2() throws Exception {
//利用反射获取需要的类
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
//获取驱动
Driver driver = (Driver)clazz.newInstance();
//获取配置信息
String url = "jdbc:mysql://localhost:3306/test";
Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "root");
//获取连接
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
~优点:利用反射机制,将com.mysql.cj.jdbc.Driver的字符串以参数形式传入方法,移植性好
方式三
@Test
public void testConnectionTest3() throws Exception {
//利用反射获取需要的类
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
//使用DriverManager(类)替代Driver
Driver driver = (Driver)clazz.newInstance();
//注册驱动
DriverManager.registerDriver(driver);
//获取配置信息
String user = "root";
String password = "root";
String url = "jdbc:mysql://localhost:3306/test";
//获取连接
Connection connection = DriverManager.getConnection(url,user,password
);
System.out.println(connection);
}
~变化:使用DriverManager代替Driver
方式四
@Test
public void testConnectionTest4() throws Exception {
//利用反射获取需要的类
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
//获取配置信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
//获取连接
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
~说明: 此代码并没有注册驱动,原因是在加载com.mysql.cj.jdbc.Driver的时候,Driver’的静态方法(静态方法随着类的加载而加载)自动注册了驱动,所以我们可以省略注册驱动的步骤
方式五
@Test
public void testConnectionTest5() throws Exception {
//获取配置信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
//获取连接
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
~说明: 省略了加载类的过程,原因是驱动的jar包自动加载了该类,不推荐使用,因为不具有通用性(mysql可以使用)
推荐方式
@Test
public void testConnectionTestFinal() throws Exception{
//.读取配置文件4个基本信息
InputStream inputStream = JdbcTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(inputStream);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClass");
//加载类
Class.forName(driverClass);
//获取连接
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
}
~说明: 将所需要的配置信息写到配置文件种,实现数据和代码的分离,解耦,推荐使用