详解SpringBoot封装使用JDBC
程序员文章站
2022-03-08 17:26:16
spring boot中可以在配置文件中直接进行数据库配置,spring.datasource.username= rootspring.datasource.password= 123456spri...
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内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!