11.零基礎開發商城專案:springboot連線mysql資料庫

1、在pom.xml檔案中新增依賴:

11.零基礎開發商城專案:springboot連線mysql資料庫

  

<dependencies></dependencies>

中新增以下程式碼,引入

jdbc、mybatis和mysql

依賴包:

<!—— jdbc ——> org。springframework。boot spring-boot-starter-jdbc <!—— mybatis ——> org。mybatis。spring。boot mybatis-spring-boot-starter 2。1。3 <!—— mysql ——> mysql mysql-connector-java runtime

3、在匯入資料庫的依賴包之後,再執行程式,就會出現以下問題:

‘url’ attribute is not specified and no embedded datasource could be configured。

問題處理:

SpringBoot框架:‘url’ attribute is not specified and no embedded datasource could be configured問題處理

3、建立資料庫表

資料庫名:

haiyeren

11.零基礎開發商城專案:springboot連線mysql資料庫

4、配置資料庫連線資訊

springboot中預設的配置檔案是

application.properties

,修改後綴名為

application.yml

,開啟編輯配置資訊:

注:

兩者的區別不大,簡單瞭解下就可以了。

哪個也可以用,主要還是看個人習慣(

application.properties和application.yml的區別

5、配置資料庫連線資訊:

spring: datasource: url: jdbc:mysql://localhost:3306/haiyeren?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com。mysql。jdbc。Driver

5、測試資料庫是否連線上

在test包中寫測試用例

11.零基礎開發商城專案:springboot連線mysql資料庫

程式碼:

@Resource DataSource dataSource; @Test public void getConnection() throws SQLException { System。out。println(dataSource。getConnection()); }

右鍵執行

11.零基礎開發商城專案:springboot連線mysql資料庫

看結果,表示已經連線上

11.零基礎開發商城專案:springboot連線mysql資料庫

(下一篇,建立一個數據表,對其進行增刪改查)