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


我有如下所示的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"


希望构建一个动态字符串。


潇潇雨雨
浏览 191回答 1
1回答

HUWWW

纯去😉func prepareInsert(table string, params map[string]interface{}) string {&nbsp; &nbsp; columns := len(params)&nbsp; &nbsp; fieldSlice := make([]string, 0, columns)&nbsp; &nbsp; for field, _ := range params {&nbsp; &nbsp; &nbsp; &nbsp; fieldSlice = append(fieldSlice, field)&nbsp; &nbsp; }&nbsp; &nbsp; fields := strings.Join(fieldSlice, ",")&nbsp; &nbsp; placeholders := prepareQueryPlaceholders(1, columns)&nbsp; &nbsp; return fmt.Sprintf(`INSERT INTO %s (%s) VALUES (%s) RETURNING %s`, table, fields, placeholders, fields)}func prepareQueryPlaceholders(start, quantity int) string {&nbsp; &nbsp; placeholders := make([]string, 0, quantity)&nbsp; &nbsp; end := start + quantity&nbsp; &nbsp; for i := start; i < end; i++ {&nbsp; &nbsp; &nbsp; &nbsp; placeholders = append(placeholders, strings.Join([]string{"$", strconv.Itoa(i)}, ""))&nbsp; &nbsp; }&nbsp; &nbsp; return strings.Join(placeholders, ",")}PLAYGROUND
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go