获取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);
 }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值