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条)

报告相同问题?

悬赏问题

  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算