当前位置:   article > 正文

数据库的五种Driver连接方式_mysql driver

mysql driver

1.使用配置文件 application.yml或者properties + springboot

以下是yml的书写方式,通常文件要放在config包下

  1. server:
  2. port: 8080
  3. spring:
  4. application:
  5. #应用名称
  6. name: database
  7. datasource:
  8. druid:
  9. driver-class-name: com.mysql.cj.jdbc.Driver
  10. url: jdbc:mysql://localhost:3306/reggie?useSSL=false&characterEncoding=UTF-8
  11. username: root
  12. password: 123445

2.在mysql.properties配置文件下

创建好properties配置文件后在一个类中连接数据库

  1. //获取配置文件中的信息
  2. Properties properties = new Properties();
  3. properties.load(new FileInputStream("src\\mysql.properties"));
  4. String root = properties.getProperty("user");
  5. String password = properties.getProperty("password");
  6. String url = properties.getProperty("url");
  7. String driver = properties.getProperty("driver");
  8. //注册驱动
  9. Class.forName(driver);
  10. //建立连接
  11. Connection connection = DriverManager.getConnection(url, root, password);

3.直接创建driver对象

  1. //1、注册驱动
  2. Driver driver = new Driver();//创建driver对象
  3. //2、得到连接
  4. String url = "jdbc:mysql://localhost:3306/database?useSSL=false&characterEncoding=UTF-8;
  5. //将用户名和密码放入Properties对象
  6. Properties properties = new Properties();
  7. properties.setProperty("user","root");
  8. properties.setProperty("password","123456");
  9. //进行连接
  10. Connection connect = driver.connect(url, properties);

4.使用DriverManager注册驱动

注意driver类在MySQL8.0是有cj的,而8.0之前的driver类是没有的

  1. //1、注册驱动
  2. //利用反射加载driver类
  3. Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
  4. Driver driver = (Driver)aClass.newInstance();
  5. //2、得到连接
  6. String url = "jdbc:mysql://localhost:3306/database?useSSL=false&characterEncoding=UTF-8";
  7. //将用户名和密码放入Properties对象
  8. Properties properties = new Properties();
  9. properties.setProperty("user","root");
  10. properties.setProperty("password","123456");
  11. //注册driver驱动
  12. DriverManager.registerDriver(driver);
  13. //进行连接
  14. Connection connect = DriverManager.getConnection(url, properties);

5.利用反射和静态方法创建

  1. //1、注册驱动
  2. //利用反射加载driver类
  3. //在加载过程中就完成了driver类的注册
  4. Class.forName("com.mysql.cj.jdbc.Driver");
  5. //2、得到连接
  6. String url = "jdbc:mysql://localhost:3306/database?useSSL=false&characterEncoding=UTF-8";
  7. //将用户名和密码放入Properties对象
  8. Properties properties = new Properties();
  9. properties.setProperty("user","root");
  10. properties.setProperty("password","123456");
  11. //不需要注册驱动就可以直接调用静态方法
  12. Connection connect = DriverManager.getConnection(url, properties);//进行连接

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号