這篇文章給大家分享的是有關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”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。