Search code examples
gosqlx

What is wrong with func NamedExec?


go version: 1.14.6
sqlx version: latest

wrong code as follow:

test := Test{
  Name: "John",
  Age:  30,
  Id:   "bskdvfjreo018g2c5pqg",
}
// table test has fields: id, name, age
_, err := sqlxdb.DB.NamedExec("NSERT INTO test(name,age,id)VALUES(:Name,:Age,:Id)", &test)
log.Println(err)

// log as follow:

// 2020/08/07 11:49:15 could not find name Name in &sqlx.Test{Id:"bskdvfjreo018g2c5pqg", Name:"John", CreateAt:0, Age:30}

Dose anyone knows whether or not the second parameter of NamedExec must pass value like ":create_at" but not like ":CreateAt" and so one?


Solution

  • As in jmoiron/sqlx issue 419, check if adding json field name mapping (using struct field tag) would help:

    type User struct {
      Id        int       `json:"id"`
      Name      string    `json:"name"`
      Bio       string    `json:"about,omitempty"`
      Active    bool      `json:"active"`
      Admin     bool      `json:"-"`
      CreatedAt time.Time `json:"created_at"`
    }
    

    Then see if passing &test to NamedExec will result in NamedExec using :created_at instead of :CreatedAt