dsfhd78978 2015-07-03 20:24
浏览 51
已采纳

如何清除数据库代码

I have a database package that contains the following code.

package database

import (
    "log"

    "github.com/jinzhu/gorm"
    // required by gorm
    _ "github.com/mattn/go-sqlite3"
)

type Podcast struct {
    ID       int `sql:"index"`
    Title    string
    RssURL   string `sql:"unique_index"`
    Paused   bool
    Episodes []Episode
}

type Episode struct {
    ID           int `sql:"index"`
    PodcastID    int
    Title        string
    EnclosureURL string `sql:"unique_index"`
    Downloaded   bool
    GUID         string `sql:"unique_index"`
    PubDate      string
}

func DBSession() (db gorm.DB) {
    sqliteSession, err := gorm.Open("sqlite3", cache.db)
    if err != nil {
        log.Fatal(err)
    }

    return sqliteSession
}

Followed by a bunch of methods that all start with the following code.

FindSomethingByID(id int) {
    db := DBSession()
    db.LogMode(false)

    // code
}

FindSomethingElse {
    db := DBSession()
    db.LogMode(false)

    // code
}

Calling DBSession and setting LogMode in each func seems bad. I just don't know how to do it better. Could someone help?

  • 写回答

2条回答 默认 最新

  • dpzlz08480 2015-07-04 00:24
    关注

    Calling gorm.Open inside every function isn't very efficient: Open opens a new connection pool, and should be called just once (see the database/sql docs, which gorm wraps).

    A simple improvement is to establish a global gorm.DB, initialise it in init() it from all of your functions - e.g.

    package database
    
    var db gorm.DB
    
    func init() {
        var err error
        // Note we use an = and not a := as our variables
        // are already initialised
        db, err = gorm.Open("sqlite3", "cache.db")
        if err != nil {
            log.Fatal(err)
        }
    
        // Turn off logging globally
        db.LogMode(false)
    }
    
    FindSomethingByID(id int) {
        err := db.Query("...")
        // code
    }
    

    This is a quick win and reduces the repetition.

    In a larger application it typically makes sense to pass dependencies (like DB pools, config params, etc.) more explicitly by wrapping them in types and creating custom handlers.

    You also might initialise the connection in your package main and pass the *gorm.DB to your database package via a func New(db *gorm.DB) function that sets a private, package-level variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改