今天写一篇关于jdbc连接数据库的五个方式,从第一种到第五种,代码逐渐简化,更具有健壮性!
url的地址如下如图:

第一种
public void TestConnection1() throws SQLException {
//获取Driver实现类的对象
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306";
//将用户名和密码封装到Properties
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
第二种:对方式一的迭代,在如下的程序中不出现第三方的api,使得程序具有更好的可移植性
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/jdbc";
//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
public void TestConnection3() throws Exception {
//1,获取Driver实现类的对象
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//2,提供另外三个连接的基本信息
String url = "jdbc:mysql://localhost:3306/jdbc";
String user = "root";
String password = "123456";
//3,注册驱动
DriverManager.registerDriver(driver);
//4,获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
第四种:可以只是加载驱动,不用显示的注册驱动了
public void TestConnection4() throws Exception {
//1,提供三个基本信息
String url = "jdbc:mysql://localhost:3306/jdbc";
String user = "root";
String password = "123456";
//2,加载Driver
Class.forName("com.mysql.jdbc.Driver");
//3,获取连接
Connection connection = DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
第五种方式:也是最终的方式,将数据库所需要的四个基本信息声明在配置文件种,通过读取配置文件的方式,获取连接
这种方式的话需要先在src目录下创建一个配置文件,一般命名为 jdbc.properties。然后写下这四个基本信息

然后代码如下,第一步就是读取配置文件,第二步的话加载驱动,第三步获取连接
//1,读取配置文件中的四个基本信息
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);
}
这也是我自己看视频学习到的一部分,一共介绍了这五种,最重要的就是第五种,也是之后要用到的一种方法,所以有小伙伴要参考的话就可以直接参考最后一种,如果有什么问题可以留言,我会尽力解决,我写的东西有错误也可以提出来,欢迎大家讨论
原文:https://www.cnblogs.com/xuan24/p/14007895.html