Mysql results.Scan(&pointerAddress) not populating fields

So i want to use the struct to populate the result but it throws and error( sql: expected 5 destination arguments in Scan, not 1), i know i have to pass the fields, in the correct order, manually . but is there a hack for doing this?

type ClientUsers struct {
	Id                        int    `json:"id"`
	FullName                  string `json:"fullName"`
	Username                  string `json:"username"`
	Email                     string `json:"email"`
	Password                  string `json:"password"`
}

for results.Next() {
	var clientUsers ClientUsers

	err := results.Scan(&clientUsers )

	if err != nil {
		fmt.Println("ERROR QUERY IN CLIENT USERS: ", err)
	}

	usersResponse = append(usersResponse, clientUsers )
}

Using the built in database/sql package you’ll be out of luck. There do exist some ORMs (object relational models) for go like this GORM - The fantastic ORM library for Golang, aims to be developer friendly.. I’ve never used it but it should get you something along the lines of what you’re looking for

1 Like

You have a few options. You could use an ORM just for the scanning functionality. For example, if you wanted to use gorm you could do something like this:

type ClientUsers struct {
	Id                        int    `json:"id"`
	FullName                  string `json:"fullName"`
	Username                  string `json:"username"`
	Email                     string `json:"email"`
	Password                  string `json:"password"`
}
var clientUsers []ClientUsers
db.Raw("select * from client_users").Scan(&clientUsers)

I don’t typically love ORMs for anything other than simple queries. In one of my projects I use GORM for CRUD to cut down on mindless select/insert queries. Then I use raw SQL for all of my more complicated/specialized queries.

You could also take a look at blockloop/scan which is more specialized to just scanning:

rows, err := db.Query("select * from client_users")

var clientUsers []ClientUsers
err := scan.Rows(&clientUsers, rows)

SQLBoiler also supports binding:

Same with sqlx:

And finally, you could implement something yourself pretty easily using reflection:

You could build a layer of abstraction on top of that using generics for example.

2 Likes

Hi, thanks a lot for the answer.