闽公网安备 35020302035485号
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
步骤2:设置GORM连接func setupDB() (*gorm.DB, error) {
db, err := gorm.Open(sqlite.Open("mydb.db"), &gorm.Config{})
if err != nil {
return nil, err
}
return db, nil
}
步骤3:在处理程序中使用GORMfunc getProductHandler(c *gin.Context) {
db, err := setupDB()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Database connection error"})
return
}
defer db.Close()
var product Product
db.First(&product, c.Param("id"))
c.JSON(http.StatusOK, product)
}
import (
"github.com/labstack/echo/v4"
"gorm.io/gorm"
)
步骤2:建立GORM连接
在Echo应用程序内初始化GORM连接:func setupDB() (*gorm.DB, error) {
db, err := gorm.Open(sqlite.Open("mydb.db"), &gorm.Config{})
if err != nil {
return nil, err
}
return db, nil
}
步骤3:在处理程序中使用GORMfunc getProductHandler(c echo.Context) error {
db, err := setupDB()
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]interface{}{"error": "Database connection error"})
}
defer db.Close()
var product Product
db.First(&product, c.Param("id"))
return c.JSON(http.StatusOK, product)
}
import (
"github.com/astaxie/beego"
"gorm.io/gorm"
)
步骤2:建立GORM连接func setupDB() (*gorm.DB, error) {
db, err := gorm.Open(sqlite.Open("mydb.db"), &gorm.Config{})
if err != nil {
return nil, err
}
return db, nil
}
步骤3:在控制器中使用GORMfunc (c *MainController) GetProduct() {
db, err := setupDB()
if err != nil {
c.Data["json"] = map[string]interface{}{"error": "Database connection error"}
c.ServeJSON()
return
}
defer db.Close()
var product Product
db.First(&product, c.Ctx.Input.Param(":id"))
c.Data["json"] = product
c.ServeJSON()
}