亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

golang?MySQL實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)表存儲(chǔ)獲取操作示例

 更新時(shí)間:2022年11月04日 14:50:45   作者:小能正在往前沖  
這篇文章主要為大家介紹了golang?MySQL實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)表存儲(chǔ)獲取操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

新建數(shù)據(jù)庫(kù)

 將部分?jǐn)?shù)據(jù)存儲(chǔ)至Mysql,使用axios通過(guò)golang搭建的http服務(wù)器獲取數(shù)據(jù)。

sql

DROP DATABASE VUE;
create database if not exists vue;
use vue;

JSON to MySQL (transform.tools)

sql

DROP DATABASE VUE;
create database if not exists vue;
use vue;
CREATE TABLE gameblog (
  id INT PRIMARY KEY AUTO_INCREMENT,
  title VARCHAR(255),
  text VARCHAR(255),
  img VARCHAR(255)
);
insert into gameblog(title,text,img) values 
("Games of the Month: surrealist solitaire puzzles","What's that? You need more games? I hear you, anonymous hapi fan.We've reached the part of the year when games start coming out fast","https://xiaonenglife.oss-cn-hangzhou.aliyuncs.com/static/pic/2022/11/20221102184434_1.jpg"),
("Games of the Month: Puzzles!","Sometimes you need a good puzzle game, just something to throw all of your attention at and ignore anything else going on. Well if that sometime for you is right now, then you're in luck because in this Games of the Month","https://xiaonenglife.oss-cn-hangzhou.aliyuncs.com/static/pic/2022/11/20221102184434_2.jpg"),
("The next hapi Creator Day is July 29th!","I don't think I'm allowed to make the entire body of this post “Thenext itch.io Creator Day is taking place on Friday July 29th.” I mean it's true, we are hosting the next itch.io Creator Day on Friday July 29th but I should probably write more here.","https://xiaonenglife.oss-cn-hangzhou.aliyuncs.com/static/pic/2022/11/20221102184434_3.jpg");
select * from gameblog;
CREATE TABLE game (
  id INT PRIMARY KEY AUTO_INCREMENT,
  title VARCHAR(255),
  text VARCHAR(255),
  img VARCHAR(255),
  price decimal(6,2) default 0,
  web boolean default 0
  # TODO 發(fā)布時(shí)間
  # TODO 瀏覽量
  # TODO 評(píng)論量
  # TODO 熱度綜合指標(biāo)
);
CREATE TABLE tag (
  id INT PRIMARY KEY AUTO_INCREMENT,
  title VARCHAR(255)
);
CREATE TABLE gametag (
  gameid INT,
  tagid INT
);
# TODO 外鍵
insert into game(id,title,text,img,price,web) values
(1,"Late Night Mop","A haunted house cleaning simulator.","https://xiaonenglife.oss-cn-hangzhou.aliyuncs.com/static/pic/2022/11/20221102193135_1.png",0,0),
(2,"an average day at the cat cafe","A haunted house cleaning simulator.","https://xiaonenglife.oss-cn-hangzhou.aliyuncs.com/static/pic/2022/11/20221102193135_2.png",0,1),
(3,"Corebreaker","A fast-paced action-platform shooter game with roguelike elements.","https://xiaonenglife.oss-cn-hangzhou.aliyuncs.com/static/pic/2022/11/20221102193135_3.png",19.99,0),
(4,"Atuel","Traverse a surrealist landscape inspired by the Atuel River in Argentina.","https://xiaonenglife.oss-cn-hangzhou.aliyuncs.com/static/pic/2022/11/20221102193135_5.png",0,0);
insert into tag values
(1,"Difficult"),
(2,"Fast-Paced");
insert into gametag values
(3,1),
(3,2),
(4,1);
DELIMITER $$
CREATE PROCEDURE gamelist()
BEGIN
	# TODO
END $$
DELIMITER ;
select a.title,a.text,img,price,web,if(group_concat(c.title separator "#") is null ,"", group_concat(c.title separator "#")) as tag from game a left join gametag b on a.id = b.gameid left join tag c on b.tagid = c.id group by a.id;

本地圖片上傳OSS圖床得到靜態(tài)資源的持久地址,我使用的是PicGo圖床工具。

SQL TO GOLANG STRUCT

在線sql轉(zhuǎn)golang struct

config.go

為了方便mysql服務(wù)器的配置,寫(xiě)一個(gè)配置文件。

golang

package mysql_vue
import "database/sql"
func GetMySQLDB() (db *sql.DB, err error) {
	dbDriver := "mysql"
	dbUser := "root"
	dbPass := "sql2008"
	dbName := "vue"
	db, err = sql.Open(dbDriver, dbUser+":"+dbPass+"@/"+dbName)
	return
}

gameblog.go

id暫時(shí)不需要,后期路由跳轉(zhuǎn)需要用到,可以先注釋。

go

package mysql_vue
import (
	"encoding/json"
	_ "github.com/go-sql-driver/mysql"
)
type Gameblog struct {
	// ID int64 `db:"id" json:"id"`
	Title string `db:"title" json:"title"`
	Text  string `db:"text" json:"text"`
	Img   string `db:"img" json:"img"`
}
func (Gameblog) TableName() string {
	return "gameblog"
}
func (Gameblog) QueryGameblog() (json_ []byte, err error) {
	// db, err := sql.Open("mysql", "root:sql2008@tcp(127.0.0.1:3306)/vue")
	db, err := GetMySQLDB()
	checkError(err)
	defer db.Close()
	// ^ 必須按照順序選取,下面的Scan需要一一對(duì)應(yīng),如果多了或少了字段會(huì)導(dǎo)致Scan錯(cuò)誤.
	results, err := db.Query("SELECT title,text,img FROM gameblog order by id desc")
	checkError(err)
	var gameBlogs []Gameblog
	for results.Next() {
		var gameBlog Gameblog
		err = results.Scan(&gameBlog.Title, &gameBlog.Text, &gameBlog.Img)
		checkError(err)
		gameBlogs = append(gameBlogs, gameBlog)
	}
	json_, err = json.Marshal(gameBlogs)
	checkError(err)
	return json_, nil
}

http

Simplify server.go

前面我們把評(píng)論相關(guān)的請(qǐng)求處理代碼寫(xiě)在了 server.go,移出到 comment.go,并在init初始化中綁定各個(gè)請(qǐng)求路徑處理函數(shù)。

comment.go

go

package server
import (
	"fmt"
	"net/http"
	"strconv"
)
type Comment interface {
	QueryComment(pid int64) (json_ []byte, err error)
	InsertComment(uid, pid int64, text string) (json_ []byte, err error)
	DeleteComment(id int64) error
}
func init() {
	http.HandleFunc("/insertComment", insertComment)
	http.HandleFunc("/deleteComment", deleteComment)
	http.HandleFunc("/queryComment", queryComment)
}
func insertComment(w http.ResponseWriter, r *http.Request) {
	....
}
func deleteComment(w http.ResponseWriter, r *http.Request) {
	....
}
func queryComment(w http.ResponseWriter, r *http.Request) {
	....
}

gameblog.go

接口用于確保某個(gè)數(shù)據(jù)庫(kù)對(duì)象實(shí)現(xiàn)了處理函數(shù),否則編譯不通過(guò)。

go

package server
import (
	"fmt"
	"net/http"
)
type Gameblog interface {
	QueryGameblog() (json_ []byte, err error)
}
func init() {
	http.HandleFunc("/queryGameblog", QueryGameblog)
}
func QueryGameblog(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		fmt.Fprintf(w, "Only GET Method")
		return
	}
	json, err := gameblog.QueryGameblog()
	if err != nil {
		fmt.Fprintf(w, "Error Delete")
		return
	}
	fmt.Fprint(w, string(json))
}

server.go

go

package server
import (
	"log"
	"net/http"
	mysql_vue "wolflong.com/vue_http/lib/mysql"
	sq3_vue "wolflong.com/vue_http/lib/sqlite"
)
var comment Comment = sq3_vue.Comment{}
var gameblog Gameblog = mysql_vue.Gameblog{}
func StartServer() {
	err := http.ListenAndServe(":1314", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

postman test api

使用 postman 測(cè)試當(dāng)前接口。

Axios

修改 HomeView.vue 的選項(xiàng)卡api,在 created 鉤子函數(shù)添加axios請(qǐng)求訪問(wèn)。

js

created() {
    this.axios
      .get("queryGameblog")
      .then((response) => {
        if (!response.data) {
          this.gameBlog = [];
          return;
        }
        this.gameBlog = response.data;
      })
      .catch((err) => {
        console.log(err);
      });
  },

gamelist.go

查詢語(yǔ)句使用兩次左連接,并用 group_concat 聚合函數(shù),聚合 tag,分解tag的過(guò)程可以從服務(wù)端遷移到客戶端進(jìn)行降低性能消耗。

go

package mysql_vue
import (
	"encoding/json"
	"strings"
)
type Gamelist struct {
	// ID    int64    `db:"id" json:"id"`
	Title string   `db:"title" json:"title"`
	Text  string   `db:"text" json:"text"`
	Img   string   `db:"img" json:"img"`
	Price float64  `db:"price" json:"price"`
	Tag   []string `db:"tag" json:"tag"` // 新添加
	Web   bool     `db:"Web" json:"web"`
}
// type Tag struct {
// 	ID    int64  `db:"id" json:"id"`
// 	Title string `db:"title" json:"title"`
// }
func (Gamelist) QueryGamelist() (json_ []byte, err error) {
	db, err := GetMySQLDB()
	checkError(err)
	defer db.Close()
	results, err := db.Query(`select a.title,a.text,img,price,web,if(group_concat(c.title separator "#") is null ,"", group_concat(c.title separator "#")) as tag from game a left join gametag b on a.id = b.gameid left join tag c on b.tagid = c.id group by a.id;`)
	checkError(err)
	var GameList []Gamelist
	for results.Next() {
		var g Gamelist
		var tag string
		err = results.Scan(&g.Title, &g.Text, &g.Img, &g.Price, &g.Web, &tag)
		g.Tag = strings.Split(tag, "#") // 這里暫且由服務(wù)端完成分解
		checkError(err)
		GameList = append(GameList, g)
	}
	json_, err = json.Marshal(GameList)
	checkError(err)
	return json_, nil
}

HTTP

gamelist.go

go

package server
import (
	"fmt"
	"net/http"
)
type Gamelist interface {
	QueryGamelist() (json_ []byte, err error)
}
func init() {
	http.HandleFunc("/queryGamelist", QueryGamelist)
}
func QueryGamelist(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		fmt.Fprintf(w, "Only GET Method")
		return
	}
	json, err := gamelist.QueryGamelist()
	if err != nil {
		fmt.Fprintf(w, "Error Delete")
		return
	}
	fmt.Fprint(w, string(json))
}

server.go

添加語(yǔ)句 var gamelist Gamelist = mysql_vue.Gamelist{}

Axios

js

this.axios
  .get("queryGamelist")
  .then((response) => {
    if (!response.data) {
      this.latestGames.games = [];
      this.mostFeatureGames.games = [];
      return;
    }
    this.latestGames.games = response.data;
    this.mostFeatureGames.games = response.data;
  })
  .catch((err) => {
    console.log(err);
  });

以上就是golang MySQL實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)表存儲(chǔ)獲取操作示例的詳細(xì)內(nèi)容,更多關(guān)于golang MySQL表存儲(chǔ)獲取的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Sublime Text3安裝Go語(yǔ)言相關(guān)插件gosublime時(shí)搜不到gosublime的解決方法

    Sublime Text3安裝Go語(yǔ)言相關(guān)插件gosublime時(shí)搜不到gosublime的解決方法

    本文主要介紹了Sublime Text3安裝Go語(yǔ)言相關(guān)插件gosublime時(shí)搜不到gosublime的解決方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2022-01-01
  • 深入理解golang的異常處理機(jī)制

    深入理解golang的異常處理機(jī)制

    Go語(yǔ)言追求簡(jiǎn)潔優(yōu)雅,所以,Go語(yǔ)言不支持傳統(tǒng)的 try…catch…finally 這種異常,下面這篇文章主要給大家介紹了關(guān)于golang的異常處理機(jī)制,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-07-07
  • 淺談go中cgo的幾種使用方式

    淺談go中cgo的幾種使用方式

    本文主要介紹了淺談go中cgo的幾種使用方式,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Go語(yǔ)言的反射機(jī)制詳解

    Go語(yǔ)言的反射機(jī)制詳解

    本文詳細(xì)講解了Go語(yǔ)言的反射機(jī)制,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07
  • Go unsafe 包的使用詳解

    Go unsafe 包的使用詳解

    這篇文章主要介紹了Go unsafe 包的使用詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-01-01
  • 最新評(píng)論