«

Golang gorm demo2

时间:2025-1-17 15:46     作者:杨佳乐     分类: Golang


package main

import (
    "fmt"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/schema"
    "time"
)

// 定义模型
type Admin struct {
    ID uint `gorm:"primaryKey;not null"`
    Username string `gorm:"size:100;not null"`
    Password string `gorm:"size:200;not null"`
    Nickname string `gorm:"size:100"`
    CreatedAt time.Time `gorm:"type:datetime"`
    UpdatedAt time.Time `gorm:"type:datetime"`
}

var DB *gorm.DB

func main(){

    dsn := "test:test@tcp(127.0.0.1:3306)/gormdemo1?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
        NamingStrategy: schema.NamingStrategy{
            TablePrefix:   "la_", // 设置表前缀
            SingularTable: false,      // 禁用表名复数
        },
    })
    if err != nil {
        fmt.Println("数据库连接失败")
    }

    DB = db

    // 创建表
    DB.AutoMigrate(&Admin{})

    // 添加数据
    admin1 := Admin{
        Username:"admin",
        Password:"pwd",
        Nickname:"nickadm",
    }

    DB.Create(&admin1)

    if admin1.ID > 0 {
        fmt.Println("创建成功")
    }

    var searchadm1 Admin

    DB.Find(&searchadm1,3)

    fmt.Println(searchadm1)

    if searchadm1.ID > 0 {
        DB.Delete(searchadm1)
    }

    fmt.Println("执行完成")

}