方式一:按部就班
@Test
public void test1() throws SQLException {
//1.实现Driver接口
Driver driver = new com.mysql.jdbc.Driver();
//2.选择数据库
String url ="jdbc:mysql://localhost:3306/test";
//url:数据库的地址
//jdbc:主协议
//mysql:子协议
//localhost:ip地址
//3306:默认mysql端口号
//test:数据库名
//3.将用户名和密码封装在Properties中
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","123456");
//4.获取连接
Connection connect = driver.connect(url, info);
System.out.println(connect);//com.mysql.jdbc.JDBC4Connection@63e31ee
}
方式二:对方式一的迭代,使得不出现api,使得具有更好的可移植性
@Test
public void test2() 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 properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
//4.获取连接
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
方式三:使用DriverManager替换Driver
DriverManger:在java.sql这个包里面,管理一组 JDBC 驱动程序的基本服务
@Test
public void test3() 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";
String user = "root";
String password = "123456";
//3.注册驱动
DriverManager.registerDriver(driver);
//4.获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
方式四:可以只加载驱动,不用显示的注册驱动
@Test
public void test4() throws Exception{
//1.提供连接的三个基本信息
String url ="jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
//2.获取Driver的实现对象
Class.forName("com.mysql.jdbc.Driver");
//相较于方式三,可以省略如下的操作
//因为mysql的Driver实现类中存在静态方法,可以注册驱动
// Driver driver = (Driver) clazz.newInstance();
// //3.注册驱动
// DriverManager.registerDriver(driver);
//4.获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
方式五:将数据库连接需要的四个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接
/* 该方法的好处:
1.实现了数据和代码的分离(实现了解耦)
2.如果需要修改配置文件的信息,可以避免程序重新打包
*/
@Test
public void test5() throws Exception{
//1.读取配置文件中的4个基本信息
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//2.加载驱动
Class.forName(driver);
//3.获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
总结:方式五最好用且最常用!