如何打开和关闭数据库连接

时间:2019-01-16 08:52:16

标签: mysql go go-gorm go-iris

我是新手,现在想创建一个大项目 我的问题是在http请求中应在哪里创建连接以及在何处关闭连接 现在我在主函数中声明db并在所有请求中使用并且不关闭连接:

package main

import (
    "fmt"
    "github.com/jinzhu/gorm"
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
    "github.com/kataras/iris/middleware/recover"
    _ "github.com/go-sql-driver/mysql"
)

var db *gorm.DB

func main() {


    port := "8080"

    app := iris.New()
    app.Configure()
    app.Logger().SetLevel("debug")

    app.Use(recover.New())

    db1, err := gorm.Open("mysql", "root:@/database?charset=utf8&parseTime=True&loc=Local")
    //db1, err := gorm.Open("mysql", "payro:AEkCpNhd@/payro_db?charset=utf8&parseTime=True&loc=Local")
    if err != nil {
        fmt.Println(err.Error())
        panic(err)
    }

    db=db1

    app.Get("/", func(i context.Context) {
        db.Exec("update tbl1 set col1=''")
        i.Next()
    })
    app.Get("/test", func(i context.Context) {
        db.Exec("update tbl2 set col2=''")
        i.Next()
    })
    _ = app.Run(iris.Addr(":"+port), iris.WithConfiguration(iris.Configuration{
        //DisableBodyConsumptionOnUnmarshal:true,

    }), iris.WithoutServerError(iris.ErrServerClosed))
}

此代码还可以吗?

1 个答案:

答案 0 :(得分:1)

您的代码可能是测试/ POC代码。 在生产项目中,您可以根据需要使用MVC或任何其他类型的体系结构。 很难确定项目的确切结构。 但是至少,您将需要创建一个db包,该包声明一个与所有与DB相关的交互的接口。 例如

type UserDBRepo interface{
   AddUser(context.Context, *User)
   GetUser(context.Context, uint64)
}

type userDBRepo struct{ //implements UserDBRepo
   *sql.DB // or whatever type gorm.Open returns
}

func NewUserDBRepo(db *sql.DB) DBRepo{
  return &dbRepo{DB: db}
}

对于该示例,以上内容基本上代表一个RDBMS表。 n个数据库表可能有n个这样的文件。 现在,从main.go调用NewUserDBRepo并将此实例传递给需要此数据库的所有服务。

相关问题