postgresql - 使用 Postgres 的 Golang UPDATE 专栏

标签 postgresql go

假设我有一个表 employments 和一个结构 Employment

type Employment struct {
    ID              int     `json:"id"`
    Created_at      string  `json:"created_at"`
    Updated_at      string  `json:"updated_at"`
    Education       string  `json:"education"`
    Job             string  `json:"job"`
    Position        string  `json:"position"`
    Business_phone  string  `json:"business_phone"`
    Next_payday     string  `json:"next_payday"`
    Employment_type int     `json:"employment_type"`
    Income          float64 `json:"income"`
    Additional      float64 `json:"additional"`
}

用户可以更新他们的employment,问题是我不知道用户想更新哪些字段。

因此,我决定遍历输入结构以获取 非 nil 字段 以生成查询字符串,例如 UPDATE employments SET position=$1, income=$2 WHERE id=$3

这是我这次得到的

func FlexibleUpdate(table_name string, str interface{}, cond string, ret string) string {

    query := "UPDATE " + table_name + " SET "
    j := 0
    m := structs.Map(str)

    for i := range m {
        if m[i] != "" && m[i] != 0 && m[i] != 0.0 && {
            j++
            query = query + strings.ToLower(i) + "=$" + strconv.Itoa(j) + ","
        }
    }
    j++

    // adding conditions
    if cond != "" {
        query = query[:len(query)-1] + " WHERE " + cond + "=$" + strconv.Itoa(j)
    }

    // return values
    if ret != "" {
        query = query + " RETURNING " + ret
    }

    return query
}

我不知道如何将输入值分配给 $1, $2, ... 以执行查询

database.DB.QueryRow(query_string, value_1, value_2, ...)

如果您有任何想法或其他解决方法,请告诉我。

最佳答案

只需将非 nil 值收集到一个 slice 中,然后在执行查询时将该 slice 与 ... 一起使用。

var values []interface{}
for i := range m {
    if v := m[i]; v != "" && v != 0 && v != 0.0 && /* you're missing a condition here */{
        j++
        query = query + strings.ToLower(i) + "=$" + strconv.Itoa(j) + ","
        values = append(values, v)
    }
}

// ....

database.DB.QueryRow(query_string, values...)

关于postgresql - 使用 Postgres 的 Golang UPDATE 专栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823566/

相关文章:

postgresql - 以原子表格式返回由自定义类型 y 组成的自定义类型 x PostgreSQL

sql - 如何在窗口函数中使用环形数据结构

go - 哪个协程(goroutines 和 kotlin coroutines)更快?

go - golang代码是否有一个既定的模式名称,看起来类似于mixin

sql - 在具有并发事务的级联 DELETE 之后插入

postgresql - Elixir Ecto : How to write a migration with belongs_to and has_many?

postgresql - 如何在 ubuntu 服务器上安装 postgis?

go - 将接口(interface)指针片转换为结构指针片的最有效方法是哪种?

go - 从字符串列表转换为 go 中的接口(interface)列表

go - 我不确定为什么索引超出范围错误