Spring Boot实践三 --数据库

一,使用JdbcTemplate访问MySQL数据库

1,在pom.xml中加入依赖:


    <!-- 添加mysql依赖 -->
     <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>5.1.45</version>
         <!-- MySQL8.x时,请使用8.x的连接器 -->
     </dependency>

     <!-- 添加jdbc依赖 -->
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>5.3.9</version>
     </dependency>
     
     <!-- 添加junit依赖 -->
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.13.2</version>
         <scope>test</scope>
     </dependency>

2,在src/main/resources/application.properties中配置数据源信息

spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

新建实体类 User ,实现 RowMapper 接口 ,该接口重写的 mapRow 方法为了实体字段和数据表字段映射(对应)。

JDBCTemplate 提供3个操作数据的方法:

execute 直接执行 sql 语句
update 进行新增、修改、删除操作
query 查询操作

你可能感兴趣的:(JAVA语言,spring,boot,数据库,后端)