gorm試用

####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
    }
相關文章
相關標籤/搜索