gorm快速使用
安裝
go get -u github.com/jinzhu/gorm
快速使用
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
//模型:爲表中的字段,記得字段名開頭大寫
type Patient struct {
//基本模型定義gorm.Model,包括字段ID,CreatedAt,UpdatedAt,DeletedAt,你可以將它嵌入你的模型,或者只寫你想要的字段,或者不需要可以乾脆不要
//gorm.Model
Patientid string
Name string
Gender int64
}
//此例爲postgresql
func main() {
db,err := gorm.Open("postgres", "host=*** user=*** dbname=*** sslmode=disable password=***")
if err != nil {
panic(err)
}
//不重新創建複數結尾的表,還是原來的表,可以利用原表中的結構,數據
db.SingularTable(true)
//defer db.Close()
// 創建
Patient{Name: "huo4", Patientid: "2000",Gender:1}
db.Create(&Patient)
// 讀取
var patient Patient
db.First(&patient , "name= ?", "huo4") // 查詢name爲huo4的patient
db.Where(&Patient {Name: "huo4"}).First(&patient)
// 更新 - 更新patient的name爲huo3
db.Model(&patient).Where("patientid= ?", "abc").Update("name", "huo3")
//update patient set name="huo3" where patientid="abc"
// 刪除 - 刪除patient
db.Delete(Patient{}, "patientid= ?", "abc")
//delete from patienti where patientid="abc"
}