SpringBoot封裝JDBC的實現步驟
Spring Boot中可以在配置文件中直接進行數據庫配置,
spring.datasource.username= root spring.datasource.password= 123456 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
SpringBoot可以直接生成數據庫對象
默認數據源為Hikari
jdbc連接
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 DataSpringbootApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() throws SQLException { System.out.println("默認數據源"); System.out.println(dataSource.getClass()); System.out.println("獲得數據庫連接"); Connection connection = dataSource.getConnection(); System.out.println(connection); System.out.println("關閉數據源"); connection.close(); } }
springboot中有很多template已經寫好可以直接拿來用
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; @RestController public class JDBCController { @Autowired JdbcTemplate jdbcTemplate; //查詢數據庫所有信息 @GetMapping("/userList") public List<Map<String,Object>> userList(){ String sql = "select * from user"; List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql); return mapList; } @GetMapping("/addUser") public String addUser(){ String sql = "insert into mybatis.user(id,name,pwd) values (4,'hhh','451651')"; jdbcTemplate.update(sql); return "update-ok"; } @GetMapping("/deleteUser/{id}") public String deleteUser(@PathVariable("id") int id){ String sql = "delete from mybatis.user where id = ?"; jdbcTemplate.update(sql,id); return "delete-ok"; } }
到此這篇關於SpringBoot封裝JDBC的實現步驟的文章就介紹到這瞭,更多相關SpringBoot封裝JDBC內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 詳解SpringBoot封裝使用JDBC
- Java Spring JdbcTemplate基本使用詳解
- SpringBoot使用JdbcTemplate訪問操作數據庫基本用法
- 教你用springboot連接mysql並實現增刪改查
- Spring框架的JdbcTemplate使用