1. 程式人生 > 其它 >spring boot 使用jdbc套用api介面執行sql並雙向傳遞

spring boot 使用jdbc套用api介面執行sql並雙向傳遞

看這篇文章前要清楚vue,element,axios,api的使用方式

1、sql語句

#建立mywebsite資料庫
create database mywebsite;
#進入mywebsite資料庫
use mywebsite;
#建立userdata表
create table userdata
(
    username varchar(30) not null comment '使用者名稱',
    userpwd varchar (30) not null comment '密碼'
);
#向userdata表新增資料
insert into userdata values ('zzj','admin');

2、建立基本的查詢功能(不含前端)

2.1、建立springboot專案

2.2、選擇所需要的外掛

spring web、JDBC API、MySQL Driver、

2.3、編寫application.properties配置檔案

application.properties主要用於配置資料庫連線資訊

application.properties

#springboot執行埠
server.port=8080
#JDBC驅動
#低於mysql8.0版本,不包含8.0
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#高於mysql8.0版本,包含8.0
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#資料庫路徑
spring.datasource.url=jdbc:mysql://localhost:3306/mywebsite?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
#資料庫使用者名稱
spring.datasource.username=root
#資料庫密碼
spring.datasource.password=admin

2.4、編寫測試類

編寫測試類,便於判斷資料庫連線是否正確

DemoApplicationTests

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        //檢視資料來源
        System.out.println(dataSource.getClass());
        //獲得連結
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        //關閉連結
        connection.close();
    }
}

2.4.1執行

如果控制檯報錯,這代表配置檔案錯誤。資料庫連線失敗。需檢查並重新配置。

如果控制檯通過,且有綠條。這表示配置檔案正常,資料庫連線正常

2.5、編寫執行sql語句的主方法

2.5.1、建立java檔案

在demo下建立一個content資料夾(package),並在content資料夾內建立個login.java檔案

2.5.2、查詢所有語句

select* from userdata

開啟剛才建立的login.java檔案並編寫程式碼

login.java

package com.example.demo.content;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class login {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("/login")
    public Object login() {
//        設定sql語句
        String sql = "select * from userdata";
//        執行sql語句並返回map
        Map<String, Object> map = jdbcTemplate.queryForMap(sql);
//        返回
        return map;
    }
}

2.5.3、執行springboot

5.3.1開啟DemoApplication檔案

2.5.3.2執行springboot

2.5.3.3這樣這表示執行成功了

2.6、檢視效果

開啟瀏覽器,並在位址列輸入http://localhost:8080/login

以上最基本的springboot查詢sql資料庫的方法。但是可以看到,得到的資料是一串json格式。這樣我們無法使用。其實這個只需要get我們想要的值就可以了。

2.7、獲得json類指定資料

2.7.1、假如是我只想獲得userpwd裡面的admin資料

login.java

是吧!

2.7.2、同樣在控制檯輸出也是如此

3、結合前端axios呼叫api來只想springboot語句

下列我用登入來做實列。登入要前端利用axios來向springboot後端傳遞資料。並且後端去抓取SQL的資料,並進行判斷。根據條件返回布林值

3.1、配置後端

3.1.1、第一步最重要的跨域問題。別看在瀏覽器可以正常執行,但是一到axios就要出毛病。

新增一個@CrossOrigin註解即可

3.1.2、登入驗證,後端要接受兩條資料。使用者名稱和密碼,並作出判斷

//required=true代表如果沒有資料就會報錯
@RequestParam(value = "username" ,required = true) String username,
@RequestParam(value = "userpwd" ,required = true) String userpwd
package com.example.demo.content;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@RestController
//跨域問題
@CrossOrigin

public class content {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("/login")
//    傳遞兩個引數
    public Object login(@RequestParam(value = "username", required = true) String username, @RequestParam(value = "userpwd", required = true) String userpwd) {
//        設定sql語句
        String sql = "select * from userdata where username = " + "'" + username + "'";
//        執行sql語句並返回map
        Map<String, Object> map = jdbcTemplate.queryForMap(sql);
//        判斷密碼是否正確
        if (userpwd.equals(map.get("userpwd"))) {
            return true;
        } else {
            return false;
        }
    }
}

3.1.3、在網頁中測試

假如是我的使用者名稱和密碼分別的root和admin

開啟瀏覽器,並在位址列輸入http://localhost:8080/login?username=zzj&userpwd=admin

如果密碼錯誤

3.2結合前端axios傳送api請求

我這裡有個登入頁面

當點選Login後前端向後端傳送api請求並接受返回,根據返回的布林值執行下面的操作

具體如何配置看,axios基本使用。

3.2.1、配置network定向後端地址及埠

import axios from 'axios'

export function request(config) {
    let newVar = axios.create({
        baseURL: 'http://localhost:8080',
        timeout:5000
    });
    return newVar(config);
}

3.2.2、配置登入介面(基於vue+elemenet)

  methods: {
    click() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          request({
            // 配置GetMapping
            url: 'login',
            params: {
              // 傳入兩個引數
              username: this.$data.user.name,
              userpwd: this.$data.user.password
            }
          }).then(res => {
            if (res.data) {
              // 返回如果為true
              this.$message({
                type: 'success',
                message: '登入成功'
              });
            } else {
              // 返回如果為false
              this.$message({
                type: 'warning',
                message: '密碼錯誤'
              });
            }
          }).catch(err => {
            // 如果後端報錯
            this.$message({
              type: 'warning',
              message: 'API錯誤'
            });
          })
        } else {
          this.$message({
            type: 'warning',
            message: '校驗錯誤'
          });
        }
      });
    }
  }

以上是基於vue+elemenet+springboot的基本的api配置及使用。