dongyao5186 2019-01-30 03:13
浏览 86

如何在golang中编写一个通用方法以在任何mysql表中插入记录

I'm creating a rest api in golang and making a POST request into a table.

For this I've created a struct. Basically the vars in struct is same as the columns in table named users.

and written a function to make a POST request. And the code is working fine, the params while making POST request is being inserted successfully in the table.

type User struct {
    ID      int
    Name    string
    Lname   string
    Country string
}


func insertUser(response http.ResponseWriter, request *http.Request)  
{
    var userDetails User
    decoder := json.NewDecoder(request.Body)
    err := decoder.Decode(&userDetails)
    defer request.Body.Close()
    if err != nil {
        returnErrorResponse(response,request, httpError)
    } else {
        httpError.Code = http.StatusBadRequest
        if userDetails.Name == "" {
             httpError.Message = "first name can't be empty"
             returnErrorResponse(response, request, httpError)
        } else if userDetails.Lname == "" {
             httpError.Message = "Last name can't be empty"
             returnErrorResponse(response, request, httpError)
        } else {
             isInserted := insertUserInDB(userDetails)
             if isInserted {
                  getAllUsers(response, request)
             } else {
                  returnErrorResponse(response, request, httpError)
             }
        }
    }
}

Here is insertUserInDB(userDetails) definition

func insertUserInDB(userDetails User) bool {
  stmt, err := db.Prepare("insert into users set Name=?, Lname=?, 
Country=?")
  if err != nil {
      fmt.Print("helper_methods.go : 118")
    fmt.Println(err)
    return false
  }

  _, queryError := stmt.Exec(tableName, userDetails.Name, 
userDetails.Lname, userDetails.Country)
  if queryError != nil {
      fmt.Print("helper_methods.go : 125")
    fmt.Println(queryError)
    return false
  }
  return true
}

Is there any way to write a common function to insert record in any of the table in the DB?

Can we create struct dynamically, or any other way?

Please help me out here.

  • 写回答

1条回答 默认 最新

  • doufei16736 2019-01-30 03:26
    关注

    Like in other languages, you can use an ORM library to do the DB translation for you, for example GORM, or you can do the translation yourself. Since you already implemented saving the data manually, see this article for how to retrieve data manually.

    If you just want to write a generic method that generates/executes SQL queries by matching struct field names you can use the reflect package of go. You will have to identify the structs fields by using reflect.TypeOf() to get the Type of your passed variable and then iterate over the StructField that you can get by using the Field() method on the Type. The StructField will reveal the Name and ValueOf() will allow you to access the Value. Name and value can then be used to construct the query. For getting a better understanding I recommend you read some articles on reflect. Like this and this.

    评论

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式