好家伙,上一篇做出來問題多多, 問題太多了,包括但不限於前端報錯:1.超出調用棧 2.跨域錯誤 vue3確實有很多我不熟悉的地方 所以,我們用回vue2吧 這裡全部用回之前的方法 Springboot連接資料庫 - 養肥胖虎 - 博客園 (cnblogs.com) 1、去新建一個spring boo ...
好家伙,上一篇做出來問題多多,
問題太多了,包括但不限於
前端報錯:1.超出調用棧 2.跨域錯誤
vue3確實有很多我不熟悉的地方
所以,我們用回vue2吧
這裡全部用回之前的方法
Springboot連接資料庫 - 養肥胖虎 - 博客園 (cnblogs.com)
1、去新建一個spring boot項目
目錄結構如下:
然後我們去到
application.properties這個文件中:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8011
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8
(註意,綠色那塊不是註釋)
TestController類:
package com.example.demo2.controller; //按文件的實際路徑來寫
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/mydb")
public class TestController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/getUsers")
public List<Map<String, Object>> getDbType(){
String sql = "select * from booktable";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
for (Map<String, Object> map : list) {
Set<Entry<String, Object>> entries = map.entrySet( );
if(entries != null) {
Iterator<Entry<String, Object>> iterator = entries.iterator( );
while(iterator.hasNext( )) {
Entry<String, Object> entry =(Entry<String, Object>) iterator.next( );
Object key = entry.getKey( );
Object value = entry.getValue();
System.out.println(key+":"+value);
}
}
}
return list;
}
@RequestMapping("/user/{id}")
public Map<String,Object> getUser(@PathVariable String id){
Map<String,Object> map = null;
List<Map<String, Object>> list = getDbType();
for (Map<String, Object> dbmap : list) {
Set<String> set = dbmap.keySet();
for (String key : set) {
if(key.equals("id")){
if(dbmap.get(key).equals(id)){
map = dbmap;
}
}
}
}
if(map==null)
map = list.get(0);
return map;
}
}
2、去資料庫建表
隨後我們訪問一下這個埠:localhost:8011/mydb/getUsers
成功拿到資料庫中的數據