zoukankan      html  css  js  c++  java
  • 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}
  • 相关阅读:
    BeyondLinux_Since1991
    TED系列:我们究竟在教AI学习什么
    TED系列:算法的影响
    TED系列:代码-下一代的通用语言
    TED系列:互联网源起故事
    Hadoop-01 搭建hadoop伪分布式运行环境
    JavaSE-26 Swing
    JavaSE-25 AWT
    JavaSE-24 多线程
    JavaSE-23 注解
  • 原文地址:https://www.cnblogs.com/wangjq19920210/p/11512426.html
Copyright © 2011-2022 走看看