Spring Boot连接到mysql docker

问题描述 投票:3回答:2

我已经旋转了mysql码头图像。

来自docker ps

bcb0a900b693 mysql:latest "docker-entrypoint..." 5 hours ago Up About an hour 0.0.0.0:3306->3306/tcp chrisbolton

我创建了一个基本的spring boot项目,我创建了一个简单的类。

@SpringBootApplication
@RestController
public class ChrisboltonServiceApplication {

public static void main(String[] args) {
    SpringApplication.run(ChrisboltonServiceApplication.class, args);
}

@Autowired
private JdbcTemplate jdbcTemplate;

@RequestMapping("/hello")
public String sayHello(){
    return "Hello";
}

@RequestMapping(path="/blogs")
public @ResponseBody Iterable<ChrisBolton> getAllUsers() {
    List<ChrisBolton> result = jdbcTemplate.query(
            "SELECT * FROM blog",
            (rs, rowNum) -> new ChrisBolton(rs.getString("author"), 
                                               rs.getString("title"), 
                                               rs.getString("content"), 
                                               rs.getDate("date"))
    );

    return result;
}

}

我已将配置放在我的application.properties

spring.main.banner-mode=off

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

当我启动我的应用程序时,我能够击中返回localhost:8080/helloHello!

当我点击localhost:8080/blogs时,我收到此错误

java.sql.SQLException: No database selected

所以我想我不明白autowired是如何完全工作的。

我试过调查beans或者使用Connection类。但是连接到我的Spring Boot实例的正确mysql方式是什么?

java mysql spring-boot database-connection
2个回答
4
投票

看起来您缺少数据库名称,例如名为test的数据库:

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

希望能帮助到你


3
投票

您遇到的问题是因为您没有提供数据库名称,因此无法对整个服务器进行查询。

格式错误:

spring.datasource.url = JDBC:MySQL的://本地主机:3306

正确格式:

spring.datasource.url = JDBC:MySQL的://本地主机:3306 /帐户

一般格式是这样的

jdbc:[数据库类型]:// [主机解析器]:[端口] / [数据库名称]

© www.soinside.com 2019 - 2024. All rights reserved.