Home > Backend Development > Golang > How to Efficiently Convert Database Rows to Structs in Go?

How to Efficiently Convert Database Rows to Structs in Go?

Barbara Streisand
Release: 2024-12-17 12:48:26
Original
370 people have browsed it

How to Efficiently Convert Database Rows to Structs in Go?

Row to Struct Conversion for Database Retrievals

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

Assuming a database table with the same schema, how can we efficiently parse a database row directly into a User struct?

Efficient Row-to-Struct Conversion

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

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

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!

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