Struct Initialization from Database Row
When dealing with database rows and structures, one common task is to initialize a struct from a database row. Here's how you can achieve this:
In the example provided, a User struct is defined to represent data retrieved from a database table with a similar schema. To parse a database row into the struct, you can use the following approach, as demonstrated in the answer given:
var row struct { age int name string } err = db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&row.age, &row.name)
This code uses the QueryRow method to retrieve a single row from the database based on a query that specifies the age condition. The Scan method is then used to populate the row struct with the retrieved values.
Notably, the QueryRow method is the recommended approach for querying a single row. For bulk retrieval, you would use the Query method and iterate through the results, scanning each row into a new struct instance similar to how it's done in the TestQuery function mentioned in the answer.
The above is the detailed content of How to Initialize a Struct from a Database Row in Go?. For more information, please follow other related articles on the PHP Chinese website!