How to select specific column from database in Golang?

WBOY
Release: 2024-06-03 13:11:56
Original
599 people have browsed it

Using the xorm library in Golang, you can easily query specific columns from the database: import the xorm library and initialize the database connection. Construct a Session for interacting with the database. Use the Cols method to specify the columns to select. Call the Find method to execute the query and obtain the results.

如何在 Golang 中从数据库中选择特定列?

#How to select specific columns from database in Golang?

In Golang, you can easily query specific columns from the database using the xorm library. xorm is a Go ORM framework that allows you to interact with databases in an intuitive way.

Steps:

  1. Import the xorm library and initialize a database connection.
  2. Construct a Session for interacting with the database.
  3. Use the Cols method to specify the columns to select.
  4. Call the Find method to execute the query and obtain the results.

Code example:

package main

import (
    "fmt"

    "github.com/go-xorm/xorm"
)

type User struct {
    Id       int    `xorm:"pk autoincr"`
    Name     string `xorm:"varchar(50)"`
    Email    string `xorm:"varchar(50)"`
    Password string `xorm:"varchar(255)"`
}

func main() {
    // 1. 初始化数据库连接
    engine, err := xorm.NewEngine("mysql", "user:password@/db_name")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer engine.Close()

    // 2. 构建一个 Session
    session := engine.NewSession()

    // 3. 指定要选择的列
    session.Cols("Id", "Name")

    // 4. 执行查询并获取结果
    users := []User{}
    if err = session.Find(&users); err != nil {
        fmt.Println(err)
        return
    }

    // 5. 遍历结果并打印
    for _, user := range users {
        fmt.Println(user.Id, user.Name)
    }
}
Copy after login

Output:

1 John
2 Mary
3 Bob
Copy after login

This example demonstrates how to use xorm Select specific columns from the database, namely Id and Name.

The above is the detailed content of How to select specific column from database in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template