1.连接数据库的工具类
package com.example.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.DriverManager;
@Component
public class MySQLConnectUtils {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driver;
public void getConnect() {
try {
Class driverObject = Class.forName(driver);
System.out.println("驱动连接结果为:" + driverObject);
Connection con = DriverManager.getConnection(url, username, password);
System.out.println("数据库连接成功:" + con);
} catch (Exception e) {
System.out.println("数据库连接失败:" + e.getMessage());
}
}
}
2.yaml中添加连接数据库的信息
spring:
datasource:
username: root
password: deng.wpxy94500
url: jdbc:mysql://localhost:3306/javaweb?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false
driver-class-name: com.mysql.jdbc.Driver
3.controller类
@Autowired
private MySQLConnectUtils mySQLConnectUtils;
@GetMapping("/testMysql")
public void testMsql(){
mySQLConnectUtils.getConnect();
}
4.依赖项
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>