Home > Backend Development > Golang > How to Initialize a Struct from a Database Row in Go?

How to Initialize a Struct from a Database Row in Go?

Susan Sarandon
Release: 2024-12-21 04:30:09
Original
261 people have browsed it

How to Initialize a Struct from a Database Row in Go?

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template