5、SpringBoot與資料訪問
阿新 • • 發佈:2021-06-23
新建一個工程專案
開啟本地的mysql資料庫
配置mysql連線資訊
編寫測試類
package com.atguigu.springboot06jdbc; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.sql.DataSource; import java.sql.Connection;import java.sql.SQLException; @SpringBootTest class SpringBoot06JdbcApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() throws SQLException { System.out.println(dataSource.getClass()); Connection connection =dataSource.getConnection(); System.out.println(connection); connection.close(); } }
執行測試類,列印連線資訊
新增一個建表語句的sql檔案
/* Navicat MySQL Data Transfer Source Server : 本地 Source Server Version : 50528 Source Host : 127.0.0.1:3306 Source Database : restful_crud Target Server Type : MYSQL Target Server Version : 50528 File Encoding : 65001 Date: 2018-03-05 10:41:40*/ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for department -- ---------------------------- DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `id` int(11) NOT NULL AUTO_INCREMENT, `departmentName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
修改配置檔案
執行住程式
建表成功
操作資料庫
package com.atguigu.springboot06jdbc.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; import java.util.Map; @Controller public class HelloController { @Autowired JdbcTemplate jdbcTemplate; @ResponseBody @RequestMapping("/query") public Map<String,Object> map(){ List<Map<String,Object>> list = jdbcTemplate.queryForList("select * from department"); return list.get(0); } }
插入一條資料到表中
重新執行主程式,這個時候表會被再建立一次,因此我們需要再次插入資料,然後訪問地址 http://localhost:8081/query
整合druid資料來源
首先引入依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.8</version> </dependency>
修改配置檔案,切換資料來源
執行測試程式,可以看到切換到druid