获取Connection的5种方式

 //方式一
 @Test
 public void test1() throws SQLException {
  //获取Driver实现类对象
  Driver driver = new Driver();
  //jdbc:mysql 协议
  //localhost:ip地址
  //zoo 数据库名
  String url = "jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC";  
  //将用户名和密码封装在properties中
  Properties info = new Properties();
  info.setProperty("user", "root");
  info.setProperty("password", "root");
  
  Connection conn=driver.connect(url, info);
  System.out.println(conn);
 }
//方式2:在如下的程序中,不出先第三方的API,有可移植性
 @Test
 public void test2() throws Exception {
  //使用反射获取Driver对象              com.mysql.cj.jdbc.Driver
  Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
  Driver driver = (Driver) clazz.newInstance();
  
  //提供连接的数据库
  String url="jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC";
  //提供需要的用户名和密码
  Properties info=new Properties();
  info.setProperty("user", "root");
  info.setProperty("password", "root");
  
  Connection conn=driver.connect(url, info);
  System.out.println(conn);
 }
 //方式3:使用DriverManager替换Driver
 @Test
 public void test3() throws Exception {
  //获取Driver实现类对象
  Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
  Driver driver =(Driver) clazz.newInstance();
  
  //注册驱动
  DriverManager.registerDriver(driver);
  
  String url="jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC";
  //获取连接
  Connection connection = DriverManager.getConnection(url, "root", "root");
  System.out.println(connection);
 }
//方式4:可以知识加载驱动,不要显示注册驱动了
 @Test
 public void test4() throws Exception {
  Class.forName("com.mysql.cj.jdbc.Driver");
  String url="jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC";
  Connection connection = DriverManager.getConnection(url, "root", "root");
  System.out.println(connection);
 }
 
 @Test
 public void test5() throws Exception {
  Class.forName("com.mysql.cj.jdbc.Driver");
  Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306?serverTimezone=UTC", "root", "root");
  System.out.println(connection);
 }
 //方式5:将数据库连接需要的4个基本信息声明在配置文件中
 @Test
 public void test6() throws Exception {
  //读取配置文件中的基本信息
  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 DrverClass = properties.getProperty("DrverClass");
  
  Class.forName(DrverClass);
  Connection connection = DriverManager.getConnection(url, user, password);
  System.out.println(connection);
 }

你可能感兴趣的:(JDBC)