In database access scenarios with structured data, it's often desirable to convert database row data into a corresponding struct. Consider the following User struct:
type User struct { Name string Id int Score int }
Assuming a database table with the same schema, how can we efficiently parse a database row directly into a User struct?
The Go database/sql package provides helpful examples, as evidenced by the following tests:
func TestQuery(t *testing.T) { type row struct { age int name string } rows, err := db.Query("SELECT|people|age,name|") got := []row{} for rows.Next() { var r row err = rows.Scan(&r.age, &r.name) got = append(got, r) } } func TestQueryRow(t *testing.T) { var row struct { age int name string } err = db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&row.age, &row.name) }
Applying these principles to your specific case, you could convert a row to a User struct as follows:
var row struct { age int name string } err = db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&row.age, &row.name)
The above is the detailed content of How to Efficiently Convert Database Rows to Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!