spring boot 如何连接本地 MySQL
为此,使用 application.properties −
spring.datasource.username=yourMySQLUserName spring.datasource.password=yourMySQLPassword spring.datasource.url=jdbc:mysql://:3306/yoruDatabaseName spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
为了理解上述语法,我们创建一个表格 −
mysql> create table demo71 −> ( −> id int, −> name varchar(20) −> ); Query OK, 0 rows affected (3.81 sec)
在表格中插入一些记录,借助插入命令 −
mysql> insert into demo71 values(100,'John'); Query OK, 1 row affected (0.13 sec) mysql> insert into demo71 values(101,'David'); Query OK, 1 row affected (0.49 sec) mysql> insert into demo71 values(102,'Bob'); Query OK, 1 row affected (0.15 sec)
在表格中使用选择语句显示记录 −
mysql> select *from demo71;
这将会产生以下输出 −
+------+-------+ | id | name | +------+-------+ | 100 | John | | 101 | David | | 102 | Bob | +------+-------+ 3 rows in set (0.00 sec)
为了验证上述 application.properties 是否与本地 MySQL 协同工作,你可以编写 spring boot 应用程序进行测试。
以下是 application.properties 文件。

以下是控制器类代码。代码如下 −
package com.demo.controller;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/table")
public class TableController {
@Autowired
EntityManager entityManager;
@ResponseBody
@GetMapping("/demo71")
public String getData() {
Query sqlQuery= entityManager.createNativeQuery("select name from demo71");
List<String> result= sqlQuery.getResultList();
StringBuilder sb=new StringBuilder();
Iterator itr= result.iterator();
while(itr.hasNext()) {
sb.append(itr.next()+" ");
}
return sb.toString();
}
}以下是主类。Java 代码如下 −
package com.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JavaMysqlDemoApplication {
public static void main(String[] args) {
SpringApplication.run(JavaMysqlDemoApplication.class, args);
}
}要运行以上内容,进入主类,右键点击并选择“Run as Java Application”。在成功执行后,你需要点击以下网址。
网址如下 −
https://:8093/table/demo71
这将会产生以下输出 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP