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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化