SpringBoot封裝JDBC的實現(xiàn)步驟
Spring Boot中可以在配置文件中直接進行數(shù)據(jù)庫配置,
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可以直接生成數(shù)據(jù)庫對象
默認數(shù)據(jù)源為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("默認數(shù)據(jù)源"); System.out.println(dataSource.getClass()); System.out.println("獲得數(shù)據(jù)庫連接"); Connection connection = dataSource.getConnection(); System.out.println(connection); System.out.println("關(guān)閉數(shù)據(jù)源"); connection.close(); } }
springboot中有很多template已經(jīng)寫好可以直接拿來用
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; //查詢數(shù)據(jù)庫所有信息 @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"; } }
到此這篇關(guān)于SpringBoot封裝JDBC的實現(xiàn)步驟的文章就介紹到這了,更多相關(guān)SpringBoot封裝JDBC內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用java生成json時產(chǎn)生棧溢出錯誤問題及解決方案
這篇文章主要介紹了使用java生成json時產(chǎn)生棧溢出錯誤問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06java根據(jù)擴展名獲取系統(tǒng)圖標和文件圖標示例
這篇文章主要介紹了java根據(jù)擴展名獲取系統(tǒng)圖標和文件圖標示例,需要的朋友可以參考下2014-03-03使用JWT作為Spring?Security?OAuth2的token存儲問題
這篇文章主要介紹了使用JWT作為Spring?Security?OAuth2的token存儲,大家經(jīng)常使用的方法有兩種一種是使用JWT作為Token傳遞,一種是使用Redis存儲Token,資源服務器本地訪問Redis校驗Token,需要的朋友可以參考下2021-12-12