1.使用配置文件 application.yml或者properties + springboot
以下是yml的书写方式,通常文件要放在config包下
server:
port: 8080
spring:
application:
#应用名称
name: database
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/reggie?useSSL=false&characterEncoding=UTF-8
username: root
password: 123445
2.在mysql.properties配置文件下
创建好properties配置文件后在一个类中连接数据库
//获取配置文件中的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String root = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//注册驱动
Class.forName(driver);
//建立连接
Connection connection = DriverManager.getConnection(url, root, password);
3.直接创建driver对象
//1、注册驱动
Driver driver = new Driver();//创建driver对象
//2、得到连接
String url = "jdbc:mysql://localhost:3306/database?useSSL=false&characterEncoding=UTF-8;
//将用户名和密码放入Properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
//进行连接
Connection connect = driver.connect(url, properties);
4.使用DriverManager注册驱动
注意driver类在MySQL8.0是有cj的,而8.0之前的driver类是没有的
//1、注册驱动
//利用反射加载driver类
Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver)aClass.newInstance();
//2、得到连接
String url = "jdbc:mysql://localhost:3306/database?useSSL=false&characterEncoding=UTF-8";
//将用户名和密码放入Properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
//注册driver驱动
DriverManager.registerDriver(driver);
//进行连接
Connection connect = DriverManager.getConnection(url, properties);
5.利用反射和静态方法创建
//1、注册驱动
//利用反射加载driver类
//在加载过程中就完成了driver类的注册
Class.forName("com.mysql.cj.jdbc.Driver");
//2、得到连接
String url = "jdbc:mysql://localhost:3306/database?useSSL=false&characterEncoding=UTF-8";
//将用户名和密码放入Properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","123456");
//不需要注册驱动就可以直接调用静态方法
Connection connect = DriverManager.getConnection(url, properties);//进行连接