乐闻世界logo
搜索文章和话题

How to read a SQLite database using GORM one row at a time

1个答案

1

When using GORM as an ORM for Go to interact with SQLite databases, if you want to read one row of data at a time, we typically use First, Last, or Take methods. These methods are provided by GORM to query a single row of data from the database.

Example: Using First Method

Suppose we have a model named User which includes ID, Name, and Email fields. We want to query the first user data.

go
package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" "log" ) type User struct { gorm.Model Name string Email string } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { log.Fatal("failed to connect database") } // Auto-migrate the schema db.AutoMigrate(&User{}) // Insert sample data db.Create(&User{Name: "Alice", Email: "alice@example.com"}) // Query the first user data var user User result := db.First(&user) if result.Error != nil { log.Fatalf("Error when fetching first user: %s", result.Error) } log.Printf("User Found: %v", user) }

In this example:

  • We first connect to the SQLite database test.db.
  • Use AutoMigrate to ensure the User table exists in the database.
  • Insert an example user Alice into the database.
  • Use First method to query the first user data and store the result in the user variable.
  • Print out the queried user information.

Other Methods

Besides using First method, GORM also provides Take and Last methods to fetch single row data. Take method fetches one row (typically the first one), while Last method fetches the last row of data. The usage of these methods is similar to First, except for the method name.

These methods are all suitable for reading a single row of data, and they can be combined with the Where clause to specify more precise query conditions, improving query accuracy and efficiency.

2024年8月12日 17:30 回复

你的答案