dssk35460
dssk35460
2019-02-13 04:32

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

已采纳

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 douyun8901 2年前

    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

    点赞 评论 复制链接分享