JDBC(二)—— 获取连接池方式

获取数据库连接的方式

方式一

Driver driver = new com.mysql.cj.jdbc.Driver();
       String url = "jdbc:mysql://localhost:3306/ujsserver?serverTimezone=GMT";
       //将用户名和密码封装在properties文件
       Properties info = new Properties();
       info.setProperty("user","root");
       info.setProperty("password","root");
       Connection conn = driver.connect(url,info);
       System.out.println(conn);

方式二

对方式一的迭代,目的是在程序中不出现第三方的API,使得程序具有更好的可移植性。

//1.获取Driver实现类对象,使用反射
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();

//2.提供要连接的数据库
String url = "jdbc:mysql://localhost:3306/ujsserver?serverTimezone=GMT";
//将用户名和密码封装在properties文件
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","root");
Connection conn = driver.connect(url, info);
System.out.println(conn);

方式三

使用DriverManager替换Driver

//1.获取Driver实现类对象,使用反射
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//注册驱动
DriverManager.registerDriver(driver);

String url = "jdbc:mysql://localhost:3306/ujsserver?serverTimezone=GMT";
String user = "root";
String password = "root";
//获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);

方式四

方式三的优化,省略一些操作,可以只是加载驱动,不用显示注册驱动了

//1.提供三个连接的基本信息
String url = "jdbc:mysql://localhost:3306/ujsserver?serverTimezone=GMT";
String user = "root";
String password = "root";

//2.加载Driver
Class.forName("com.mysql.cj.jdbc.Driver");

//获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);

为什么能省略?

在Mysql的Driver实现类中声明了如下操作:

static {
   try {
       java.sql.DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
  } catch (SQLException E) {
       throw new RuntimeException("Can't register driver!");
  }
}

方式五(最终版)

将数据库连接的基本配置信息加载到配置文件中,通过读取配置文件获取数据库连接

//1.读取配置文件的信息
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");

Properties pros = new Properties();
pros.load(is);

String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driver = pros.getProperty("driver");

//2.加载Driver
Class.forName(driver);

//3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);

优点:

  • 实现了数据与代码的分离,解耦。

  • 如果需要修改文件配置文件信息不需要程序重新打包

原文地址:https://www.cnblogs.com/whystudyjava/p/14115633.html