1. 首先创建一个Spring Boot项目被勾选以下选项。
代码如下:
2. 配置项目的依赖,Spring Boot和MySQL连接驱动。
在JdbcTemplate的配置文件pom.xml加入以下代码:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.15</version> </dependency>
3. 使用JdbcTemplate创建一个MySQL数据库,并设计一个适当
的数据表。
在以下文件中创建sql文件
sql文件中代码如下:创建数据表并进行添加虚拟数据。
4. 编写Spring Boot的配置文件,配置JdbcTemplate与MySQL的连接信息。
在application类配置类中添加一下代码:
spring: datasource: url: jdbc:mysql://localhost:3306/DataApplication?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver sql: init: schema-locations: classpath:db/carschema.sql mode: always continue-on-error: true data-locations: classpath:db/cardata.sql
3306为数据库端口/DataApplication在mysql中创建的数据库名称
classpath:所对应路径的sql文件,连接数据库。
5. 在项目中创建一个DAO类,用JdbcTemplate完成对数据库的增删查改。
6. 在项目中创建一个Controller类,提供相应的接口访问数据库操作。
运行成功后,在MySQL数据库中会出现以下数据表:
如果运行失败,检查sql文件中是否语法出错,最简便的方法把sql中语法粘贴至mysql数据库进行运行,就能查找到哪个语法出错。
7. 实现以下功能:
对应的地址栏要相同。
- 插入一条数据到数据库:
插入成功后:会多一行数据