Springboot整合JDBC
一、整合jdbc使用
1.创建一个新的springboot项目,添加mysqlApi和MysqlDriver以及Springweb依赖;
2.连接数据库;
3.使用Test查看数据源和连接:
@SpringBootTest
class SpringbootDataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看数据源:class com.zaxxer.hikari.HikariDataSource
System.out.println(dataSource.getClass());
//获得连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
4.创建一个JDBCController类实现jdbc的增删改查:
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping("/getData")
public List<Map<String,Object>> getData(){
String sql = "select * from mybatis.user";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
@RequestMapping("/add")
public String AddData(){
String sql = "insert into mybatis.user values(4,'王者','123123')";
jdbcTemplate.update(sql);
return "insert-ok";
}
@RequestMapping("/update/{id}")
public String UpdateData(@PathVariable Integer id){
String sql = "update mybatis.user set name=?,pwd=? where id="+id;
Object[] objects = new Object[2];
objects[0]="小王";
objects[1]="12321";
jdbcTemplate.update(sql,objects);
return "update-ok";
}
@RequestMapping("/del/{id}")
public String delData(@PathVariable Integer id){
String sql ="delete from mybatis.user where id="+id;
jdbcTemplate.update(sql);
return "del-ok";
}
}