golang經常使用庫:gorilla/mux-http路由庫使用
golang經常使用庫:配置文件解析庫-viper使用
golang經常使用庫:操做數據庫的orm框架-gorm基本使用html
gorm中一般用struct來映射字段. gorm教程中叫模型定義
好比咱們定義一個模型Model:mysql
type User struct { gorm.Model UserId int64 `gorm:"index"` //設置一個普通的索引,沒有設置索引名,gorm會自動命名 Birtheday time.Time Age int `gorm:"column:age"`//column:一個tag,能夠設置列名稱 Name string `gorm:"size:255;index:idx_name_add_id"`//size:設置長度大小,index:設置索引,這個就取了一個索引名 Num int `gorm:"AUTO_INCREMENT"` Email string `gorm:"type:varchar(100);unique_index"`//type:定義字段類型和大小 AddressID sql.NullInt64 `gorm:"index:idx_name_add_id"` IgnoreMe int `gorm:"_"` Description string `gorm:"size:2019;comment:'用戶描述字段'"`//comment:字段註釋 Status string `gorm:"type:enum('published', 'pending', 'deleted');default:'pending'"` }
上面的gorm.Model 定義以下:git
type Model struct { ID uint `gorm:"primary_key"`//primary_key:設置主鍵 CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time }
固然咱們也能夠不用gorm.Model,本身定義一個差很少的類型
若是你用ID,系統會自動設爲表的主鍵,固然咱們能夠本身定義主鍵:
好比:
github
// 使用`AnimalID`做爲主鍵 type Animal struct { AnimalID int64 `gorm:"primary_key"` Name string Age int64 }
直接看下面的例子:createtable.go
sql
package main import ( "database/sql" "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "time" ) type User struct { gorm.Model UserId int64 `gorm:"index"` Birtheday time.Time Age int `gorm:"column:age"` Name string `gorm:"size:255;index:idx_name_add_id"` Num int `gorm:"AUTO_INCREMENT"` Email string `gorm:"type:varchar(100);unique_index"` AddressID sql.NullInt64 `gorm:"index:idx_name_add_id"` IgnoreMe int `gorm:"_"` Description string `gorm:"size:2019;comment:'用戶描述字段'"` Status string `gorm:"type:enum('published', 'pending', 'deleted');default:'pending'"` } //設置表名,默認是結構體的名的複數形式 func (User) TableName() string { return "VIP_USER" } func main() { db, err := gorm.Open("mysql", "root:root@/gormdemo?charset=utf8&parseTime=True&loc=Local") if err != nil { fmt.Println("connect db err: ", err) } defer db.Close() if db.HasTable(&User{}) { //判斷表是否存在 db.AutoMigrate(&User{}) //存在就自動適配表,也就說原先沒字段的就增長字段 } else { db.CreateTable(&User{}) //不存在就建立新表 } }
上面的gorm.Open()操做,若是想指定主機話,就須要加上括號 ()
例如:user:password@(localhost)/dbname?charset=utf8&parseTime=True&loc=Local
上面的程序中,先新建了一個數據庫名叫 gormdemo
,而後運行:go run createtable.go
, 成功運行後,數據庫就會出現一張名爲 vip_user
的表。
數據庫
新建一個gormdemo的數據庫,而後執行下面的sql語句,就會創建一個animals的表,裏面還有一些測試數據
app
CREATE TABLE `animals` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT 'galeone', `age` int(10) unsigned DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of animals -- ---------------------------- INSERT INTO `animals` VALUES ('1', 'demo-test', '20'); INSERT INTO `animals` VALUES ('2', 'galeone', '30'); INSERT INTO `animals` VALUES ('3', 'demotest', '30'); INSERT INTO `animals` VALUES ('4', 'jim', '90'); INSERT INTO `animals` VALUES ('5', 'jimmy', '10'); INSERT INTO `animals` VALUES ('6', 'jim', '23'); INSERT INTO `animals` VALUES ('7', 'test3', '27');
例子:create.go
框架
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type Animal struct { ID int64 Name string Age int64 } func main() { db, err := gorm.Open("mysql", "root:root@/gormdemo?charset=utf8&parseTime=true&loc=Local") if err != nil { fmt.Println("connect db error: ", err) } defer db.Close() animal := Animal{Name: "demo-test", Age: 20} db.Create(&animal) }
說明:上面的這個例子,本身在mysql中建立一個animals的數據表,字段爲id,name,age
測試
select.go
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type Animal struct { ID int64 Name string Age int64 } //https://gorm.io/zh_CN/docs/query.html func main() { db, err := gorm.Open("mysql", "root:root@/gormdemo?charset=utf8&parseTime=true&loc=Local") if err != nil { fmt.Println("connect db error: ", err) } defer db.Close() //根據逐漸查詢第一條記錄 var animal Animal db.First(&animal) fmt.Println(animal) //根據逐漸查詢最後一條記錄 var animal2 Animal db.Last(&animal2) fmt.Println(animal2) //指定某條記錄(僅當主鍵爲整型時可用) var animal3 Animal db.First(&animal3, 2) fmt.Println(animal3) //where條件 //符合條件的第一條記錄 var animal4 Animal db.Where("name = ?", "demotest2").First(&animal4) fmt.Println("where : ", animal4, animal4.ID, animal4.Name, animal4.Age) //符合條件的全部記錄 var animals5 []Animal db.Where("name = ?", "galeone").Find(&animals5) fmt.Println(animals5) for k, v := range animals5 { fmt.Println("k:", k, "ID:", v.ID, "Name:", v.Name, "Age:", v.Age) } //IN var animals6 []Animal db.Where("name IN (?)", []string{"demo-test", "demotest2"}).Find(&animals6) fmt.Println(animals6) //LIKE var animals7 []Animal db.Where("name like ?", "%jim%").Find(&animals7) fmt.Println(animals7) //AND var animals8 []Animal db.Where("name = ? AND age >= ?", "jim", "24").Find(&animals8) fmt.Println(animals8) //總數 var count int var animals9 []Animal db.Where("name = ?", "galeone").Or("name = ?", "jim").Find(&animals9).Count(&count) fmt.Println(animals9) fmt.Println(count) //Scan, 原生查詢 var animals10 []Animal db.Raw("SELECT id, name, age From Animals WHERE name = ? AND age = ? ", "galeone", "30").Scan(&animals10) fmt.Println("Scan: ", animals10) //原生查詢,select all var animals11 []Animal rows, _ := db.Raw("SELECT id,name FROM Animals").Rows() //注意:上面的 select id,name 後面不能寫成 * 代替,否則出來的結果都是默認0值 //像這樣結果: ALL: [{0 0} {0 0} {0 0} {0 0} {0 0} {0 0} {0 0}] //Scan 後面是什麼字段,select 後面就緊跟什麼字段 for rows.Next() { var result Animal rows.Scan(&result.ID, &result.Name) animals11 = append(animals11, result) } fmt.Println("ALL: ", animals11) //output:ALL: [{1 demo-test 0} {2 galeone 0} {3 demotest2 0} {4 galeone 0} {5 galeone 0} {6 jim 0} {7 jimmy 0}] //select 查詢 var animal12 Animal db.Select("name,age").Find(&animal12) //只查詢name,age字段,至關於select name,age from user fmt.Println("select: ", animal12) // db.Select([]string{"name", "age"}).Find(&animal12) // fmt.Println("select2: ", animal12) }
update.go
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type Animal struct { ID int64 Name string Age int64 } func main() { db, err := gorm.Open("mysql", "root:root@/gormdemo?charset=utf8&parseTime=true&loc=Local") if err != nil { fmt.Println("connect db error: ", err) } defer db.Close() ///根據一個條件更新 //根據條件更新字段值, //後面加Debug(),運行時,能夠打印出sql db.Debug().Model(&Animal{}).Where("id = ? ", 4).Update("name", "jimupdate") //UPDATE `animals` SET `name` = 'jimupdate' WHERE (id = 4) //另一種寫法: 根據條件更新 var animal Animal animal = Animal{ID: 3} db.Debug().Model(animal).Update("name", "demotest2update") // db.Debug().Model(&animal).Update("name", "demotest2update") // 這種寫法也能夠 //UPDATE `animals` SET `name` = 'demotest2update' WHERE `animals`.`id` = 3 /// 多個條件更新 db.Model(&Animal{}).Where("id = ? AND age = ?", 4, 45).Update("name", "jimupdate3") //UPDATE `animals` SET `name` = 'jimupdate2' WHERE (id = 4 AND age = 45) /// 更新多個值 db.Debug().Model(&Animal{}).Where("id = ?", 4).Update(Animal{Name: "jim", Age: 90}) // UPDATE `animals` SET `age` = 90, `name` = 'jim' WHERE (id = 4) animal2 := Animal{ID: 5} db.Debug().Model(&animal2).Update(map[string]interface{}{"name": "jimm", "age": 100}) //UPDATE `animals` SET `age` = 100, `name` = 'jimm' WHERE `animals`.`id` = 5 }
delete.go
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type Animal struct { ID int64 Name string Age int64 } func main() { db, err := gorm.Open("mysql", "root:root@/gormdemo?charset=utf8&parseTime=true&loc=Local") if err != nil { fmt.Println("connect db error: ", err) } defer db.Close() db.Debug().Where("id = ?", 13).Delete(&Animal{}) // DELETE FROM `animals` WHERE (id = 13) db.Debug().Delete(&Animal{}, "id = ? AND age = ?", 14, 10) //DELETE FROM `animals` WHERE (id = 14 AND age = 10) }
在db後面直接加上 Debug(), 好比delete.go 裏面的例子