38

golang操作gorm基本

 4 years ago
source link: https://www.tuicool.com/articles/iQ77nai
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前言

对于golang中使用gorm操作mysql,可能其他的操作都是固定的,唯一麻烦的就是字段的映射。

gorm允许自己定义一个表的结构映射,但是,golang中,首字母大写来表示public或者private,而gorm在做映射的时候,大写的转化是不一样的。这里就做一下区分。

1.直接使用表的机构映射

比如你用find之类不需要写表名称,直接用结构获取的情况下,struct的机构和数据库中的结构要一致,不一样的用 gorm:"column:nameSpace" ,这个来说明,column里面就是你想要映射的名称。

2.定义自己的结构

这么定义的话,就不要求完全一样。

这里又分两种

一,你如果没有用row,直接一条语句末尾加Scan(&struct),这么来接受的,需要字段名称对应,也可以这个可以首字母大写,前提是数据库中表没有其他大写,如果数据库表内字段有其他大写,则使用 gorm:"column:nameSpace" 来重新定义在数据库中使用的名称。

二,没有直接返回结果,而是返回一个rows,在next内接受结果,这样的话,就不用注重名称,只需要顺序对应好即可。比如你的struct第一个成员代表name,那就写在表name的那一列上就好。

以下是一个小例子,注释里面的是另一种写法

package main

import (
    "log"

    _ "github.com/go-sql-driver/mysql"
)

type TestTable struct {
    NameSpace string `gorm:"column:nameSpace"`
    Age       int
    Address   string
}

func main() {
    db, err := DbOpen("mysql", "root:123456@(127.0.0.1:3306)/stbtest?charset=utf8")
    if err != nil {
        log.Println(err)
        return
    }
    defer DbClose(db)
    st := TestTable{}
    db.Table("test").Where("nameSpace=? and age = ?", "aa", 1).Scan(&st)
    // row, err := db.Table("test").Rows()
    // for row.Next() {
    //  row.Scan(&st.NameSpace, &st.Age, &st.Address)
    //  log.Println("||", st.NameSpace, "||", st.Age, "||", st.Address)
    // }
    log.Println("||", st.NameSpace, "||", st.Age, "||", st.Address)
    if err != nil {
        log.Println(err)
        return
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK