共计 2411 个字符,预计需要花费 7 分钟才能阅读完成。
链接 mysql
xorm
go get -u github.com/xormplus/xorm
conf
在 conf 目录中减少 db.go
申明mysql
的链接构造体
package conf
import (
"github.com/json-iterator/go"
"io/ioutil"
)
type DbConf struct {
Driver string `json:"DbName"`
Host string `json:"DbHost"`
Port string `json:"DbPort"`
User string `json:"DbUser"`
Pwd string `json:"DbPwd"`
DbName string `json:"DbDbName"`
}
// MasterDbConfig 主库配置
var MasterDbConfig = DbConf{
Driver: "mysql",
Host: "192.168.1.1",
Port: "3306",
User: "root",
Pwd: "123456",
DbName: "go",
}
datasource
在 datasource 目录中减少dbhelper.go
链接数据库
package datasource
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
"log"
"myCommunity/conf"
"sync"
)
var (
masterEngine *xorm.Engine
lock sync.Mutex
)
func DbHelper() *xorm.Engine {
// 判断是否曾经存在
if masterEngine != nil {return masterEngine}
lock.Lock()
defer lock.Unlock()
// 判断是否曾经存在 因为加锁 想要从新判断是否存在
if masterEngine != nil {return masterEngine}
c := conf.MasterDbConfig
driverSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
c.User, c.Pwd, c.Host, c.Port, c.DbName)
log.Println(driverSource)
engine, err := xorm.NewEngine(c.Driver, driverSource)
if err != nil {log.Fatalf("DbHelper.DbInstanceMaster,", err)
return nil
}
// Debug 模式,打印全副的 SQL 语句,帮忙比照,看 ORM 与 SQL 执行的对照关系
engine.ShowSQL(true)
masterEngine = engine
return engine
}
测试 jdbc
批改 main.go
package main
import (
"log"
"myCommunity/datasource"
)
func main() {queryString, errr := datasource.DbHelper().QueryString("select * from title")
if errr != nil {return}
log.Println(queryString)
....
执行 main.go 测试 xorm
链接 mysql
是否失常 执行后控制台输入
[xorm] [info] 2021/07/06 22:33:50.857913 [SQL] select * from title
2021/07/06 22:33:51 [map[id:1 name: 百度] map[id:2 name: 谷歌]]
查询数据库胜利
数据库设计
在 https://www.yanshisan.cn/Link… 中应用博客、留言、日记、友链模板。
依据这些模块简略设计一下数据库。数据库表对应 models 如下
article(博客表)
package models
import "time"
type Article struct {
Id int `form:"id"`
Title string `form:"title"`
Content string `form:"content"`
UserId int `form:"userId"`
CreateTime time.Time `form:"createTime"`
UpdateTime time.Time `form:"updateTime"`
// 拜访次数
Visit int `form:"visit"`
// 分类
Types string `form:"types"`
}
diary(日记表)
package models
import "time"
type Diary struct {
Id int `form:"id"`
Content string `form:"content"`
CreateTime time.Time `form:"createTime"`
}
message(留言)
package models
import "time"
type Message struct {
Id int `form:"id"`
Ip string `form:"ip"`
Content string `form:"content"`
// 回复 id
Pid int `form:"pid"`
CreateTime time.Time `form:"createTime"`
}
title(友链题目)
package models
type Title struct {
Id int `form:"id"`
Name string `form:"name"`
}
link(友链)
package models
type Link struct {
Id int `form:"id"`
// 友链题目 id
Pid int `form:"pid"`
Title string `form:"title"`
Path string `form:"path"`
}
数据库曾经 xorm 搭建实现 下一步开始性能开发
正文完