dssk35460 2019-02-12 20:32
浏览 301
已采纳

两种不同形式的数据库连接字符串

I have two different codes to connect postgresql with golang first code like this

connStr := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", user, password, dbName)

and the second one like this

connStr := fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", user, password, dbName)

What's the difference between them? And when do I have to use the second one?

  • 写回答

1条回答 默认 最新

  • douyun8901 2019-02-12 23:43
    关注

    Both of them work and as far as I know there is not real difference between them.

    import "database/sql"
    
    import _ "github.com/lib/pq"
    
    connStr := fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", user, password, dbName)
    db, err := sql.Open("postgres", connStr)
    

    ///////////////////////////////

    import "database/sql"
    
    import _ "github.com/lib/pq"
    
    connStr := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", user, password, dbName)
    db, err := sql.Open("postgres", connStr)
    if err != nil {
        log.Fatal(err)
    }
    

    More info you can find here: https://godoc.org/github.com/lib/pq

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部