golang中gorm包的操作
阿新 • • 發佈:2018-12-11
1.簡單的連線和CURD
package main import ( "github.com/jinzhu/gorm" _ "github.com/go-sql-driver/mysql" "time" ) type User struct { User_id int `gorm:"primary_key"` //指定主鍵並自增 Name string Pwd string CreatedAt time.Time UpdatedAt time.Time } func main() { //建立連線 db, err := gorm.Open("mysql", "root:
[email protected](127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local") if err != nil { panic("連線資料庫失敗") } defer db.Close() // 自動遷移模式 //db.AutoMigrate(&User{}) user := User{} //新增 db.Create(&User{Name: "qwwqw", Pwd: "qwqwqwqwqw"}) //查詢 db.First(&user, 1).Scan(&user) //修改 user.Name = "jinzhu 2" db.Save(&user) //刪除 db.Where("user_id = ?",2).Delete(User{}) }
2.深入查詢操作
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/go-sql-driver/mysql"
"time"
"fmt"
)
type User struct {
User_id int `gorm:"primary_key"` //指定主鍵並自增
Name string
Pwd string
CreatedAt time.Time
UpdatedAt time.Time
Car []Car `gorm:"ForeignKey:User_id;AssociationForeignKey:User_id"` //(一對多)指定外來鍵和關聯外來鍵
}
type Car struct {
Car_id int32 `gorm:"primary_key"`
User_id int
Car_name string
Car_gongli string
}
func main() {
//建立連線
db, err := gorm.Open("mysql", "root: [email protected](127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("連線資料庫失敗")
}
defer db.Close()
// 自動遷移模式
db.AutoMigrate(&User{}, &Car{})
/**
* 查詢單條資料
* &是為了獲取結構體的記憶體地址,這樣指標傳遞速度較快
*/
user := User{}
db.First(&user, 10)
////SELECT * FROM users WHERE user_id = 10 LIMIT 1;
db.Where("user_id = ?", 9).First(&user)
////SELECT * FROM users WHERE user_id = 9 LIMIT 1;;
fmt.Println(&user)
/**
* 查詢多條資料
*
*/
users := []User{}
db.Find(&users)
////SELECT * FROM users
db.Where("user_id = ? and name = ?", 10, "jinzhu").Find(&users)
//// SELECT * FROM users WHERE name = "jinzhu" AND user_id = 20;
db.Where("created_at > ?", "2018-09-22 08:50:09").Or("updated_at < ?", "2018-09-22 08:50:09").Order("created_at asc").Find(&users)
//// SELECT * FROM users WHERE created_at = '2018-09-22 08:50:09' OR updated_at < '2018-09-22 08:50:09';
fmt.Println(users)
/**
* 關聯查詢
* 一對多 多對一 多對多
*/
db.Where("user_id = ?", 10).Preload("Car").Find(&user)
db.Where("user_id = ?", 10).Preload("Car","car_name like ?","%田%").Find(&user)
fmt.Println(&user)
}