我已经旋转了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/hello
的Hello!
当我点击localhost:8080/blogs
时,我收到此错误
java.sql.SQLException: No database selected
所以我想我不明白autowired
是如何完全工作的。
我试过调查beans
或者使用Connection
类。但是连接到我的Spring Boot
实例的正确mysql
方式是什么?
看起来您缺少数据库名称,例如名为test的数据库:
spring.datasource.url=jdbc:mysql://localhost:3306/test
希望能帮助到你
您遇到的问题是因为您没有提供数据库名称,因此无法对整个服务器进行查询。
格式错误:
spring.datasource.url = JDBC:MySQL的://本地主机:3306
正确格式:
spring.datasource.url = JDBC:MySQL的://本地主机:3306 /帐户
一般格式是这样的
jdbc:[数据库类型]:// [主机解析器]:[端口] / [数据库名称]