2017-08-29 191 views
1

我已经分解了mysql泊坞窗图像。Spring Boot连接到mysql docker

docker ps

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

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

@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/hello返回Hello!

当我打localhost:8080/blogs ,我得到这个错误

java.sql.SQLException: No database selected

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

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

回答

3

看起来你丢失的数据库名称,例如数据库名为test:

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

希望它可以帮助

+0

OMG就是这样。那些非常小的事情之一。谢谢! –

1

,你所面临的问题是,因为你没有提供数据库名称,因此无法为整个服务器执行查询。

格式错误:

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

右格式:

spring.datasource.url = JDBC :mysql:// localhost:3306/accounts

通用格式就是这样

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