How to Convert a Database Row into a Struct in Go

Converting a database row into a struct in Go typically involves using a package like a database/sql for basic database operations or an ORM (Object-Relational Mapping) library like gorm for more advanced features.

Here’s a step-by-step guide for both approaches:

Method 1: Using database/sql

Let’s assume you have the following table named users:

CREATE TABLE users (
  id INT PRIMARY KEY,
  name TEXT,
  email TEXT
);

You can define a Go struct like this:

type User struct {
  ID int
  Name string
  Email string
}

To retrieve a row and scan it into the struct:

import (
  "database/sql"
  _ "github.com/go-sql-driver/mysql"
)

func GetUserByID(db *sql.DB, userID int) (*User, error) {
  var u User
  err := db.QueryRow("SELECT id, name, email FROM users WHERE id = ?", userID)
           .Scan(&u.ID, &u.Name, &u.Email)
  if err != nil {
    return nil, err
  }
  return &u, nil
}

Method 2: Using gorm

First, you need to define the struct with gorm-specific tags:

type User struct {
  ID int `gorm:"primaryKey"`
  Name string
  Email string
}

To retrieve a row and scan it into the struct:

import (
  "gorm.io/gorm"
)

func GetUserByID(db *gorm.DB, userID int) (*User, error) {
  var u User
  result := db.First(&u, userID)
  if result.Error != nil {
    return nil, result.Error
  }
  return &u, nil
}

In both cases, properly handle database connection, error handling, and other related concerns. The above examples are simplified to focus on scanning rows into structs.

That’s it!

Leave a Comment