为了账号安全,请及时绑定邮箱和手机立即绑定

使用 map[string]interface{} 输入在 golang 中为 postgresql

使用 map[string]interface{} 输入在 golang 中为 postgresql

Go
潇潇雨雨 2023-02-21 12:51:47
我有如下所示的map[string]interface 输入用户user := map[string]interface{}{       "firstname": firstname,       "lastname":  lastname,       "country":   country,       "email":     email,   }上面给出的值来自其他函数作为变量,因此未在“”中指示。例如,我需要从上面的接口生成如下动态查询:"INSERT INTO USERTABLE (key1, key2, key3, key4) VALUES (val1, val2, val3, val4) RETURNING id迭代器将在其中计算键和值并生成如下查询"INSERT INTO USERTABLE (firstname, lastname, country, email) VALUES (firstname, lastname, country, email) RETURNING userid"希望构建一个动态字符串。
查看完整描述

1 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

纯去😉


func prepareInsert(table string, params map[string]interface{}) string {

    columns := len(params)

    fieldSlice := make([]string, 0, columns)

    for field, _ := range params {

        fieldSlice = append(fieldSlice, field)

    }

    fields := strings.Join(fieldSlice, ",")


    placeholders := prepareQueryPlaceholders(1, columns)

    return fmt.Sprintf(`INSERT INTO %s (%s) VALUES (%s) RETURNING %s`, table, fields, placeholders, fields)

}


func prepareQueryPlaceholders(start, quantity int) string {

    placeholders := make([]string, 0, quantity)

    end := start + quantity

    for i := start; i < end; i++ {

        placeholders = append(placeholders, strings.Join([]string{"$", strconv.Itoa(i)}, ""))

    }

    return strings.Join(placeholders, ",")

}

PLAYGROUND


查看完整回答
反对 回复 2023-02-21
  • 1 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信