获取数据库的连接方式(循循渐进)
方式一:
@Test
public void testConnection1() throws SQLException {
// 实例化mysql的驱动
Driver driver = new Driver();
// 提供连接信息,包括url,user,password
String url = "jdbc:mysql://localhost:3306/eancollect";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "0000");
// 建立连接
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
方式二:使用反射
@Test
public void testConnection2() throws Exception {
// 通过反射动态获取驱动,并实例化
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
// 提供连接信息
String url = "jdbc:mysql://localhost:3306/eancollect";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "0000");
// 建立连接
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
方式三:使用DriverManger(驱动管理器)替换Driver
@Test
public void testConnection3() throws Exception {
// 通过反射动态获取驱动,并实例化
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
// 提供连接信息
String url = "jdbc:mysql://localhost:3306/eancollect";
String user = "root";
String password = "0000";
//注册驱动
DriverManager.registerDriver(driver);
// 建立连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
方式四:(优化)使用DriverManger(驱动管理器)替换Driver
可以显式的加载驱动,不用显式的注册驱动,因为Driver中有静态方法,在加载类的时候,就会注册驱动
@Test
public void testConnection4() throws Exception {
// 提供连接信息
String url = "jdbc:mysql://localhost:3306/eancollect";
String user = "root";
String password = "0000";
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
方式五(final版):将数据库连接需要的4个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接
此种方式的好处?
- 实现了数据与代码的分离。实现了解耦
- 如果需要修改配置文件信息,可以避免程序重新打包。
配置文件:
@Test
public void testConnection5() throws Exception {
//默认是项目下的文件
FileInputStream fis = new FileInputStream(new File("hello3.txt"));
//默认是src下的文件
//InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String url =pros.getProperty("url") ;
String user =pros.getProperty("user") ;
String password =pros.getProperty("password") ;
String driverClass =pros.getProperty("driverClass") ;
// 加载驱动
Class.forName(driverClass);
// 建立连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}