一、準備工作
配置MySQL資料庫之前,需要先安裝好MySQL資料庫,並創建一個新的資料庫和用戶,給予該用戶在該資料庫的許可權。
二、添加MySQL依賴
在pom.xml文件的dependencies節點下添加MySQL的驅動依賴。例如:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency>
三、配置數據源
在application.properties或application.yml中,添加以下數據源的配置信息:
#MySQL數據源配置 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
其中,修改url中對應的資料庫名稱、username和password為創建好的資料庫和用戶的名稱和密碼,driver-class-name為MySQL的驅動類名。
四、測試資料庫連接
可以通過創建一個Controller,在其中添加@Autowired注入數據源,然後調用getConnection()方法測試資料庫是否能正常連接。
@RestController public class TestController { @Autowired private DataSource dataSource; @GetMapping("/test") public String test() throws SQLException { Connection connection = dataSource.getConnection(); return "資料庫連接成功!"; } }
然後在瀏覽器中訪問http://localhost:8080/test,如果返回「資料庫連接成功!」說明資料庫連接正常。
五、總結
通過以上幾步的操作,成功配置了SpringBoot和MySQL資料庫的連接。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/193593.html