Golang:Gorm 連接數(shù)據(jù)庫
Golang 寫的灯抛,開發(fā)人員友好的 ORM 庫,當然 Xorm 也非常的優(yōu)秀音瓷,但是我就是不用你看氣人不
安裝依賴
go get -u github.com/jinzhu/gorm
連接數(shù)據(jù)庫
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("初始化數(shù)據(jù)庫成功......")
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
}
//創(chuàng)建表
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
}
//分頁數(shù)據(jù)
func (post *Comment) GetPages(pageSize int,page int) (comments []Comment){
Db.Where("id >= ?",3).Limit(pageSize).Offset((page-1)*pageSize).Find(&comments)
return comments
}
//刪除數(shù)據(jù)
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("初始化數(shù)據(jù)庫成功......")
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,實際開發(fā)過程中還是建議使用數(shù)據(jù)庫的事務操作,遇到未知的錯誤時進行數(shù)據(jù)庫回滾,以此保證后臺數(shù)據(jù)庫的穩(wěn)定
否則有時候將會出現(xiàn)一些讓人腦仁疼的事情厕鹃,比如造成 mysql 超時死鎖,解決可以參考 http://www.gzky.live/article/詳解MySQL(InnoDB)是如何處理死鎖的
Gorm支持很多的數(shù)據(jù)庫驅動,這里只是演示了 Mysql 的一些操作催训,有了面對對象的數(shù)據(jù)庫操作混稽,一切操作都將變得簡單,維護也更加方便
參考文檔 http://gorm.book.jasperxu.com
哦天吶痘系,該死,我要去吃飯了 .....
歡迎轉載城豁,但要聲明出處雳旅,不然我順著網(wǎng)線過去就是一拳。
個人技術博客:http://www.gzky.live