2017-08-29 189 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:[數據庫類型]:// [主機解析器]:[端口]/[數據庫名稱]