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.
#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:
xorm
library and initialize a database connection. Session
for interacting with the database. Cols
method to specify the columns to select. 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) } }
Output:
1 John 2 Mary 3 Bob
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!