To simplify the code, and prevent from passing similar arguments again and again, I created a method Put
for some structures as below.
For example, the reason why UID
is not used here is because UID
was set as an auto increase value.
type User struct {
UID int
Name string
Username string
Password string
}
func (user *User) Put(db *sql.DB, query string) (sql.Result, error) {
return db.Exec(query, u.UID, u.Name, u.Username, u.Password)
}
func main() {
db := ...
u := &User{...}
u.Put(db, `INSERT INTO user(name, username, password) VALUES ($2, $3, $4);`)
}
But I get the error below
pq: could not determine data type of parameter $1
(SQL driver is https://github.com/lib/pq)
In your query
$2, $3...$N
is the index of the argument that is passed in as extra arguments todb.Exec()
and they must start from$1
(if you usedatabase/sql
package).I think in your case you may to change
Put
method signature (addstruct values extractor
)and use one like