dqkxo44488 2018-04-09 08:18
浏览 45
已采纳

golang如何将这两个功能结合在一起?

I want to learn to write clean code in golang, my problem is: I have two function and I need to combined to become only one, this is my actual code:

func db_execute(sql_cmd string) bool {

    db, err := sql.Open("mysql", mysql_login)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        log.Fatal(err)
    }

    stmt, err := db.Prepare(sql_cmd)
    if err != nil {
        fmt.Print(err.Error())
    }
    _, err = stmt.Exec()

    if err != nil {
        fmt.Print(err.Error())
        return false
    }

    return true
}

func db_tabela_select(cod_cliente string) (id string, cod1 string, cod2 string, cod3 string) {

    db, err := sql.Open("mysql", mysql_login)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        log.Fatal(err)
    }

    err = db.QueryRow("select id, cod1, cod2, cod3 from db_tabela WHERE `cliente`=? LIMIT 1;", cod_cliente).Scan(
                        &id, &cod1, &cod2, &cod3)

    switch {
        case err == sql.ErrNoRows:
                log.Printf("No codice cliente with that ID.")
        case err != nil:
                log.Printf("database select problems")
        default:
                fmt.Printf("Client code is %s %s %s
", cod1, cod2, cod3)
    }

    return id, cod1, cod2, cod3
}

How can I combine these 2 function in one? These functions have different input and different output.

  • 写回答

1条回答 默认 最新

  • dongmi4734 2018-04-09 12:34
    关注

    You shouldn't "combine" those functions. What's common in them, move them "out", e.g. to a 3rd function which can be called by these 2.

    Also, connecting to a DB should not be a "local" operation, it should only be done once, e.g. in a package init() function.

    Moreover, functions that may fail (db operations are typical examples of these) should return an error, so it can be inspected and dealt with at the caller.

    This is a simpler, more robust and more idiomatic solution to your example:

    var db *sql.DB
    
    func init() {
        var err error
        db, err = sql.Open("mysql", "db_url_string")
        if err != nil {
            log.Fatal(err)
        }
    
        if err = db.Ping(); err != nil {
            log.Fatal(err)
        }
    }
    
    func dbExecute(sql_cmd string) error {
        stmt, err := db.Prepare(sql_cmd)
        if err != nil {
            return err
        }
        _, err = stmt.Exec()
        return err
    }
    
    func dbTabelaSelect(cod_cliente string) (id, cod1, cod2, cod3 string, err error) {
        query := "select id, cod1, cod2, cod3 from db_tabela WHERE 'cliente'=? LIMIT 1"
        err = db.QueryRow(query, cod_cliente).Scan(&id, &cod1, &cod2, &cod3)
        return
    }
    

    Example using these functions:

    func main() {
        defer db.Close() // Graceful shutdown
    
        if err := dbExecute("some_SQL"); err != nil {
            fmt.Print("SQL execution failed: %v", err)
        }
    
        id, cod1, cod2, cod3, err := dbTabelaSelect("someID")
        switch {
        case err == sql.ErrNoRows:
            log.Printf("No codice cliente with that ID.")
        case err != nil:
            log.Printf("database select problems")
        default:
            fmt.Printf("Client code is %s %s %s %s
    ", id, cod1, cod2, cod3)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?