Golang:Gorm 连接数据库
Golang 写的,开发人员友好的 ORM 库,当然 Xorm 也非常的优秀,但是我就是不用你看气人不
安装依赖
go get -u github.com/jinzhu/gorm
连接数据库
func init(){
var err error
mysql_conn := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", "root","wocao", "127.0.0.1", 3306, "iris_blog")
//赋值给全局变量 Db 没有 := 就是赋值
Db, err = gorm.Open("mysql", mysql_conn)
if err != nil{
panic(err)
}
fmt.Println("初始化数据库成功......")
Db.LogMode(false) //是否开启log
Db.AutoMigrate( &models.Article{},&models.G_count{}) //自动迁移 跟py一样
}
定义模型
type Comment struct{
ID int
Content string `sql:"not null"`
Author string `sql:"not null"`
}
来一些增删改查的操作
func (post *Comment) GetCounts() (count int64){
Db.Model(post).Count(&count)
return
}
//创建表
func (post *Comment) CreateComments() error{
return Db.Create(post).Error
}
//获取全部内容
func (post *Comment) GetComments() (comments []Comment){
Db.Find(&comments)
return comments
}
//获取id为1 的字段
func (post *Comment) GetUser() (comments []Comment, err error) {
Db.Model(post).Where("id = ?", 1).Find(&comments)
err = Db.Model(&post).Related(&comments).Error
return
}
//更新字段
func (post *Comment) UpdateComments() (comments []Comment, err error){
//Db.Model(post).Update("id",1).Update("author",33333)
Db.Model(post).Where("id = ?", 1).Updates(map[string]interface{}{"author": 9999,"content":444444,"create_time":time.Now()})
err = Db.Model(post).Related(&comments).Error
return
}
//分页数据
func (post *Comment) GetPages(pageSize int,page int) (comments []Comment){
Db.Where("id >= ?",3).Limit(pageSize).Offset((page-1)*pageSize).Find(&comments)
return comments
}
//删除数据
func (post *Comment) DeleteComments() (err error) {
return Db.Where("id = ?", 2).Delete(&post).Error
}
整体看一看
package cap
import (
"fmt"
_ "github.com/go-sql-driver/mysql" //初始化驱动
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
"time"
)
type Comment struct{
ID int
Content string `sql:"not null"`
Author string `sql:"not null"`
}
var Db *gorm.DB
func init(){
var err error
Db, err = gorm.Open("mysql", "root@/go_test?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil{
panic(err)
}
fmt.Println("初始化数据库成功......")
Db.LogMode(true)
Db.AutoMigrate(&Comment{})
}
func (post *Comment) GetCounts() (count int64){
Db.Model(post).Count(&count)
return
}
func (post *Comment) CreateComments() error{
return Db.Create(post).Error
}
func (post *Comment) GetComments() (comments []Comment){
Db.Find(&comments)
return comments
}
func (post *Comment) GetUser() (comments []Comment, err error) {
Db.Model(post).Where("id = ?", 1).Find(&comments)
err = Db.Model(&post).Related(&comments).Error
return
}
func (post *Comment) UpdateComments() (comments []Comment, err error){
//Db.Model(post).Update("id",1).Update("author",33333)
Db.Model(post).Where("id = ?", 1).Updates(map[string]interface{}{"author": 9999,"content":444444,"create_time":time.Now()})
err = Db.Model(post).Related(&comments).Error
return
}
func (post *Comment) GetPages(pageSize int,page int) (comments []Comment){
Db.Where("id >= ?",3).Limit(pageSize).Offset((page-1)*pageSize).Find(&comments)
return comments
}
func (post *Comment) DeleteComments() (err error) {
return Db.Where("id = ?", 2).Delete(&post).Error
}
如何调用
package main
import (
"fmt"
"gorm使用/cap"
)
func main(){
//定义字段
comment := cap.Comment{
Content:"WELCOME TO 鬼子口音 TO WELCOME",
Author:"鬼子口音",
}
err := comment.CreateComments()
if err != nil{
panic(err)
}
c := cap.Comment{}
comments := c.GetComments()
for _,p := range comments{
fmt.Println(p.Author,p.Content)
fmt.Printf("%T",p)
}
//err := c.DeleteComments()
//if err != nil{
// panic(err)
//}
count := c.GetCounts()
fmt.Println(count)
lll := c.GetPages(5,3)
for _,p := range lll{
fmt.Println(p.ID,p.Author)
}
}
上面只是一些 demo,实际开发过程中还是建议使用数据库的事务操作,遇到未知的错误时进行数据库回滚,以此保证后台数据库的稳定
否则有时候将会出现一些让人脑仁疼的事情,比如造成 mysql 超时死锁,解决可以参考 http://www.gzky.live/article/详解MySQL(InnoDB)是如何处理死锁的
Gorm支持很多的数据库驱动,这里只是演示了 Mysql 的一些操作,有了面对对象的数据库操作,一切操作都将变得简单,维护也更加方便
参考文档 http://gorm.book.jasperxu.com
哦天呐,该死,我要去吃饭了 …
欢迎转载,但要声明出处,不然我顺着网线过去就是一拳。
个人技术博客:http://www.gzky.live