链接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/Links 中使用博客、留言、日记、友链模板。
根据这些模块简单设计一下数据库。数据库表对应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 搭建完成 下一步开始功能开发