上图是百度百科的一段话,JDBC在这里不多说了,相信各位一定都已经很熟悉了,如果大家不熟悉,可以自行学习:https://www.jianshu.com/p/0a0199ba98a6
1.修改pom文件,添加坐标
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> </parent> <groupId>com.neuedu</groupId> <artifactId>09-spring-boot-jdbc</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- SpringBoot启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 添加JDBC的支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- 添加MySQL数据库支持 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> </project>
2.编写配置文件(application.yml)
spring: datasource: username: root password: root url: jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver
3.编写获取数据库连接及默认数据源的Controller
package com.neuedu.controller; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * SpringBoot HelloWorld * @author 清水三千尺 * */ @Controller public class GetConnection { @Autowired DataSource dataSource; @RequestMapping("/getConn") @ResponseBody public String getConnection() throws SQLException { //获取默认的数据源 Class<? extends DataSource> class1 = dataSource.getClass(); //获取数据库连接 Connection conn = dataSource.getConnection(); return "默认的数据源:" + class1 + "<br/> 数据库连接:" + conn; } }
4.创建启动类
package com.neuedu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * SpringBoot 启动类 * @author 清水三千尺 * */ @SpringBootApplication public class App { public static void main(String[] args) throws Exception { SpringApplication.run(App.class, args); } }
5.测试
到此为止能够获取到数据库连接,其他的CURD操作在这里就不进行演示了。