####gorm试用--属于mysql
###数据库链接git
db, err := gorm.Open("mysql", "root:rootpassword@/dbname?charset=utf8&parseTime=True&loc=Local") if err != nil { panic("链接数据库失败") } defer db.Close()
###建立表github
if !db.HasTable(&User{}) { db.CreateTable(&User{}) } if !db.HasTable(&Profile{}) { db.CreateTable(&Profile{}) }
###准备些数据golang
oneuser := User{Name: "wayne"} db.Create(&oneuser) oneprofile := Profile{UserID: 1, Name: "wayne1"} db.Create(&oneprofile)
###查询数据sql
user := &User{} db.Debug().Where(&User{Name: "wayne"}).First(&user) profile := &Profile{} db.Debug().Model(&user).Related(&profile) fmt.Println(user) fmt.Println(profile)
###总体代码数据库
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) func main() { db, err := gorm.Open("mysql", "root:rootpassword@/dbname?charset=utf8&parseTime=True&loc=Local") if err != nil { panic("链接数据库失败") } defer db.Close() if !db.HasTable(&User{}) { db.CreateTable(&User{}) } if !db.HasTable(&Profile{}) { db.CreateTable(&Profile{}) } oneuser := User{Name: "wayne"} db.Create(&oneuser) oneprofile := Profile{UserID: 1, Name: "wayne1"} db.Create(&oneprofile) user := &User{} // 查询用户,条件为名字为wayne,将结果放到user变量里 db.Debug().Where(&User{Name: "wayne"}).First(&user) profile := &Profile{} // 依据以前查询的user为条件,查询profile,查询profile的条件为user的id db.Debug().Model(&user).Related(&profile) fmt.Println(user) fmt.Println(profile) } type User struct { gorm.Model Name string } type Profile struct { gorm.Model UserID int User User Name string }