golang MySQL实现对数据库表存储获取操作示例
来源:脚本之家
时间:2022-12-22 16:34:45 499浏览 收藏
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《golang MySQL实现对数据库表存储获取操作示例》,介绍一下MySQL、表存储、获取表,希望对大家的知识积累有所帮助,助力实战开发!
新建数据库
将部分数据存储至Mysql,使用axios通过golang搭建的http服务器获取数据。
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 发布时间 # TODO 浏览量 # TODO 评论量 # TODO 热度综合指标 ); 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图床得到静态资源的持久地址,我使用的是PicGo图床工具。
SQL TO GOLANG STRUCT
config.go
为了方便mysql服务器的配置,写一个配置文件。
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暂时不需要,后期路由跳转需要用到,可以先注释。
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需要一一对应,如果多了或少了字段会导致Scan错误. 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
前面我们把评论相关的请求处理代码写在了 server.go,移出到 comment.go,并在init初始化中绑定各个请求路径处理函数。
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
接口用于确保某个数据库对象实现了处理函数,否则编译不通过。
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 测试当前接口。
Axios
修改 HomeView.vue 的选项卡api,在 created 钩子函数添加axios请求访问。
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
查询语句使用两次左连接,并用 group_concat 聚合函数,聚合 tag,分解tag的过程可以从服务端迁移到客户端进行降低性能消耗。
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, "#") // 这里暂且由服务端完成分解 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
添加语句 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实现对数据库表存储获取操作示例》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
-
244 收藏
-
235 收藏
-
157 收藏
-
101 收藏
-
138 收藏
-
244 收藏
-
300 收藏
-
103 收藏
-
166 收藏
-
266 收藏
-
175 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 507次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习
-
- 疯狂的枕头
- 这篇博文太及时了,好细啊,真优秀,收藏了,关注作者了!希望作者能多写Golang相关的文章。
- 2023-01-10 19:24:35
-
- 朴素的饼干
- 很有用,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢博主分享文章!
- 2022-12-31 20:08:11
-
- 精明的红酒
- 这篇技术文章太及时了,太全面了,很好,码起来,关注老哥了!希望老哥能多写Golang相关的文章。
- 2022-12-29 06:17:14
-
- 正直的大叔
- 受益颇多,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,看完之后很有帮助,总算是懂了,感谢作者分享技术文章!
- 2022-12-29 02:48:43
-
- 傲娇的水壶
- 太细致了,已收藏,感谢老哥的这篇技术贴,我会继续支持!
- 2022-12-26 16:50:34
-
- 懦弱的帽子
- 这篇技术贴太及时了,太详细了,受益颇多,码住,关注作者大大了!希望作者大大能多写Golang相关的文章。
- 2022-12-25 12:11:27
-
- 害羞的夕阳
- 这篇博文出现的刚刚好,老哥加油!
- 2022-12-24 19:48:51