gorm demo

package main

import (
    "fmt"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type Product struct {
    Id  int 
    Num int 
}

func main() {
    db, err := gorm.Open("sqlite3", "/root/test.db")
    if err != nil {
        fmt.Println("连接数据库失败")
    }   
    defer db.Close()

    // 自动迁移模式
    db.AutoMigrate(&Product{})

    // 创建
    test := Product{Id: 100, Num: 200}
    db.Create(&test)
    fmt.Println("test.id is ", test.Id)

    // 读取
    var product Product

    // 询id为1的product
    db.First(&product, 100)
    fmt.Println("product.id is ", product.Id)

    // 询code为l1212的product
    db.First(&product, "Num = ?", 200)
    fmt.Println("product.num is ", product.Num)

    // 更新 - 更新product的price为2000
    db.Model(&product).Update("Num", 2000)

    var tests []Product
    db.Find(&tests)
    fmt.Println("Find tests: ", tests)

    for index, line := range tests {
        fmt.Println("index", index, " line ", line)
    }

    // 删除 - 删除product
    db.Delete(&product)
}

运行结果如下:

[root@wangjq test]# go run gorm_v1.go 
test.id is  100
product.id is  100
product.num is  200
Find tests:  [{100 2000}]
index 0  line  {100 2000}

 

posted @ 2019-09-12 16:06  salami_china  阅读(596)  评论(0编辑  收藏  举报