spring boot配置mysql

2025-10-14 13:24:32

1、创建spring boot项目,如下图所示

spring boot配置mysql

2、添加maven依赖,代码如下

<dependency>           

<groupId>org.springframework.boot</groupId>           

<artifactId>spring-boot-starter-jdbc</artifactId>       

</dependency>       

<dependency>           

<groupId>mysql</groupId>           

<artifactId>mysql-connector-java</artifactId>           

<scope>runtime</scope>       

</dependency>

spring boot配置mysql

3、修改application.properties配置文件,添加如下代码

spring.datasource.url=jdbc:mysql://localhost:3306/test

spring.datasource.username=root

spring.datasource.password=root

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring boot配置mysql

4、添加测试代码,在启动方法中添加如下代码,用JdbcTemplate操作数据库

@SpringBootApplication

public class SpringBootMysqlApplication {

         public static void main(String[] args) {

        ConfigurableApplicationContext context =

                SpringApplication.run(SpringBootMysqlApplication.class, args);

        JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class);

        List<Map<String, Object>> result =

                jdbcTemplate.queryForList("SELECT * FROM USER");

        System.out.println(result);

         }

}

spring boot配置mysql

5、点击启动按钮,启动程序

spring boot配置mysql

6、在控制台打印了user表的所有信息,如下图所示,mysql配置成功,数据连接池也创建成功

spring boot配置mysql

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢