看java连接数据库的发展过程:
1.JDBC直连;
2.数据库连接池;
3.QueryRunner;
4.JPA框架:MyBatis、Hibernate、Spring data jpa;
5.通用Mapper;
Java数据库操作系列入门教程:JDBC基本使用、DBCP基本使用、Hibernate/Spring data jpa/MyBatis基本使用
https://blog.csdn.net/fightingXia/article/details/80715281
查看连接的数量:
https://www.cnblogs.com/liuyuhangCastle/p/9595458.html
概念:
数据源:datasource的概念、不同连接池对应的datasource类
https://blog.csdn.net/fightingXia/article/details/82555999
连接池:使用数据库连接池的好处、直接用DriverManager获取连接的坏处
https://blog.csdn.net/caidie_huang/article/details/52639567
一 使用JDBC连接数据库
JAVA连接数据库最基本的方式:直接用JDBC连接,过程包括:注册驱动、获取连接、创建statement、执行sql、获取返回结果集
https://blog.csdn.net/qq_38449518/article/details/80501246
# 一 导入maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
# 二 修改默认配置
无
# 三 创建实体类
public class User {
private Long id;
private String userNaame;
// getter、setter略
}
# 四 Controller、Service、DAO
1.Controller
@Controller
public class MyController {
@Autowired
private MyService myService;
@GetMapping("test/{id}")
@ResponseBody
public String queryNameById(@PathVariable Long id){
try {
return this.myService.queryNameById(id);
} catch (Exception e) {
e.printStackTrace();
return "访问错误";
}
}
}
2.Service
@Service
public class MyService {
@Autowired
private MyDAO myDAO;
public String queryNameById(Long id) throws SQLException, ClassNotFoundException {
return this.myDAO.queryNameById(id);
}
}
3.DAO
@Repository
public class MyDAO {
public String queryNameById(Long id) throws SQLException, ClassNotFoundException {
String driver = "com.mysql.cj.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/newdb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
String username="root";
String password="123456";
Class.forName(driver);